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!!
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With