Question

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?

Was it helpful?

Solution

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);
});

OTHER TIPS

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">

I too was needing a solution to the paste problem, and I figured out something that will work for me. A person can still use the Edit > Paste in the browsers menu, but Ctrl-V, as well as right click paste is handled. Tested in FF,IE,Opera,Safari,Chrome:

<!DOCTYPE html>
<html>
<head>
    <title>Only Allow Certain Characters</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
    <br>
    <form id="myform" action="">
        <input id="element1" name="mytext1" type="text">
        <input id="element2" name="mytext2" type="text">
    </form>
<script>
    /* removes evil chars while typing */
    (function($){
        $.fn.disableChars = function(a) {

            a = $.extend({
                allow: ''
            }, a);

            b = a.allow.split('');
            for ( i=0; i<b.length; i++) b[i] = "\\" + b[i];
            a.allow = b.join('');

            var regex = new RegExp('[^a-z0-9' + a.allow + ']', 'ig');

            $(this)
            .bind('keyup blur', function() {
                if (this.value.search(regex) != '-1') {
                    this.value = this.value.replace(regex, '');
                }
            })
            .bind('contextmenu',function () {return false});

        }
    })(jQuery);

    $("#element1").disableChars();
    $("#element2").disableChars({allow:".,:-() "});
</script>
</body>
</html>

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top