How can i deny user from entering special characters in textbox using jquery?
special characters are like \ / ? * [ or ]
How can i deny user from entering special characters in textbox using jquery?
special characters are like \ / ? * [ or ]
i think you can achieve this using javascript only
call the below function in KeyPress event of text box
function AlphaNumericOnly(e,isAlphaonly)
{
// copyright 1999 Idocs, Inc. http://www.idocs.com
var key = [e.keyCode||e.which];
var keychar = String.fromCharCode([e.keyCode||e.which]);
keychar = keychar.toLowerCase();
if(isAlphaonly=='true')
checkString="abcdefghijklmnopqrstuvwxyz";
else
checkString="abcdefghijklmnopqrstuvwxyz0123456789";
if ((key==null) || (key==0) || (key==8) ||
(key==9) || (key==13) || (key==27) )
return true;
else if (((checkString).indexOf(keychar) > -1))
return true;
else
return false;
}
check the keycodes within a keydown or keyup event handler.
$('input').bind('keydown', function(e){
if(e.shiftKey){
switch(e.which){
case 55:{ // slash
return(false);
}
case 187:{ // *
return(false);
}
// and so forth
}
}
});
Like @Reigel pointed out, listening for keyboard entries can easily be bypassed by simply pasting the content so I think you would be better off with something like the jQuery Validation plugin.
It has tons of features, like custom validation rules so you can have it validate after your own custom rules (obviously). Below is an example of how you can have the validation trigger when the watched field's content changes (rather than waiting until the form is submitted), be it by typing or pasting:
$("#myTextField").change(function() {
if(!$(this).valid()) {
/* do something, show an alert, or whatever you need it to do */
}
});
I won't go into greater detail on how to use this plugin because SO is already full of examples, but I hope it does set you on the right direction.