views:

721

answers:

5

I am using the .alphanumeric plugin for jQuery which is certainly doing what I would expect as users type directly into the textbox. But, if a user were to copy and paste a value into the text box, all bets are off.

$("#<%= txtNumber.ClientID %>").alphanumeric({allow:"-"});

I can certainly do this:

$(document).ready(function() {
    $("#<%= txtNumber.ClientID %>").blur(function() {
        $("#<%= txtNumber.ClientID %>").val(
            RemoveInvalidCharacters(
                $("#<%= txtNumber.ClientID %>").val()
            )
        );
    });
});

//FUNCTION REMOVES ANY ; IN TEXT TO PREVENT SQL INJECTION
function RemoveInvalidCharacters(text) {
     return text.replace(';', '');
}

But... I'd rather not have to kluge up my code even further with .blur() functions. Are there any other ways around this?

A: 

Copy and Paste is definitely a challenge for masked inputs.

Have you considered "encoding" special characters when the form is submitted as opposed to when the user enters values? We do the same thing to allow users to enter the < and > characters in TextBoxes (we convert them to &lt; and &gt; via javascript and then back in to < and > in the code behind.

Ken Browning
+3  A: 

Handling the paste event is fairly straightforward. I'm using this technique in my masked input plugin with good results. Feel free to browse the source to see it in use.

Here is the relevant bits modified for your example above.

var pasteEventName = $.browser.msie ? 'paste' : 'input';
$("#<%= txtNumber.ClientID %>").bind(pasteEventName, function() {
   setTimeout(function() { 
      RemoveInvalidCharacters(
         $("#<%= txtNumber.ClientID %>").val()
      ); 
   }, 0);
});
Josh Bush
This is very useful.. thanks!
Aeon
A: 

This way you will not prevent an SQL injection. I’m not required to use your form, I can make mine and POST it to your script. Even easier: I can disable javascript and go drop your database.

Instead, check the input validity on server side.

The easiest ways are escaping it or using parametrised queries.

Ilya Birman
A: 

I found this solution here: http://www.devcurry.com/2009/10/allow-only-alphanumeric-characters-in.html

<script type="text/javascript">
$(function() {
 $('input.alpha').keyup(function() {
  if (this.value.match(/[^a-zA-Z0-9 ]/g)) {
   this.value = this.value.replace(/[^a-zA-Z0-9 ]/g, '');
  }
 });
});
</script>

<input type="text" name="test" value="" class="alpha">
James Moberg