Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do not allow Paste any non alphanumeric characters

I don’t want user to allow pasting of any non Alphanumeric characters on a text box. How do I restrict this in Javascript? Thanks!!

like image 796
user228777 Avatar asked Dec 29 '22 09:12

user228777


1 Answers

Using jQuery, this is one way to do it:

HTML:

​<form name='theform' id='theform' action=''>
<textarea id='nonumbers' cols='60' rows='10'> </textarea>
</form>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

JavaScript:

$().ready(function(){
    $("textarea#nonumbers").keyup(removeextra).blur(removeextra);
});
function removeextra() {
    var initVal = $(this).val();
    outputVal = initVal.replace(/[^0-9a-zA-Z]/g,"");       
    if (initVal != outputVal) {
        $(this).val(outputVal);
    }
};

Try it out here.

EDIT: As remarked in the comments, the original (using the .keyup() event) would have left open the possibility of pasting via the mouse context menu, so I've added a .blur() event. .change() would have been possible too, but there are reports of bugginess. Another option is using .focusout(). Time to experiment...

like image 88
chryss Avatar answered Dec 30 '22 23:12

chryss