How to disable special characters from paste in a textbox?
Im using a onkeypress event handler
function disableOtherChar(evt) {
var charCode;
charCode = (evt.which) ? evt.which : evt.keyCode;
var ctrl;
ctrl = (document.all) ? event.ctrlKey : evt.modifiers & Event.CONTROL_MASK;
if ((charCode > 47 && charCode < 58) || (charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123) || charCode == 8 || charCode == 9 || charCode == 45 || (ctrl && charCode == 86) || ctrl && charCode == 67) {
return true;
} else {
$(":text").live("cut copy paste", function (e) {
e.preventDefault();
});
return false;
}
}
But it doesnt block special characters when pasting, only in entering,
suppose that you have a Input
<input id="textInput" name="textInput">
and you have the following script to validate the copy:
$(function(){
$( "#textInput" ).bind( 'paste',function()
{
setTimeout(function()
{
//get the value of the input text
var data= $( '#textInput' ).val() ;
//replace the special characters to ''
var dataFull = data.replace(/[^\w\s]/gi, '');
//set the new value of the input text without special characters
$( '#textInput' ).val(dataFull);
});
});
});
You could use a 3rd party plugin like jquery.alphanum, it works for paste (ctrl+v) too. The code looks like this :
$("input").alphanum();
Or you could use it in a more spceficied way like this :
$("#elemet").alphanum({ allow : "asd", disallow : "!@#", allowUpper : false });
The above code you need to add it into your JQuery declaration.
I mention the fact that you can also modify the blacklist array from the script jquery.alphanum.js
on line 124. You will find a function name getBlacklistAscii, in that you modify var blacklist = ...
to what suits you.
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