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!!
I'm not sure how you can prevent pasting, but you can filter the contents either on the submit or on the change event.
It's better to validate form - check this great jQuery's plugin - http://docs.jquery.com/Plugins/Validation/ and you can use the "number" rule : http://docs.jquery.com/Plugins/Validation/Methods/number. Really simple and easy to tune thing!
You can use this on blue event of text box.
function remove()
{
var otxt=document.getElementById('txt1');
var val=otxt.value;
for(i=0;i<val.length;i++)
{
var code=val.charCodeAt(i);
if(!(code>=65 && code<=91) && !(code >=97 && code<=121) && !(code>=48 && code<=57))
{ otxt.value=""; return ; }
}
}
<input type="text" id="txt1" onblur="remove();" />
It will remove all value of text box when you input non alphanumeric value.
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);
}
};
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...
Assuming:
<textarea id="t1"/>
You could modify the onchange
event handler for the textarea to strip out anything not alphanumeric:
document.getElementById('t1').onchange = function () {
this.value = this.value.replace(/\W/,'');
}