$(function(){
$('input[name="username"]').keydown(function(key){
if (jQuery.inArray(key.keyCode,
[8,37,39,48,49,50,51,52,53,54,55,56,57,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90])
== -1 || key.shiftKey ){
return false;
}
});
});
What this does is Ajax validation on the text characters, it only lets me enter letters from a-z and 0-9, and not any other characters, but i want it to allow me the _ (underscore) character as well.
The
keypressevent handler tries to catch invalid characters before they are input into the field, to prevent a distracting ‘jumping’ effect when invalid characters are shown and onkeyupare removed again. Note thatevent.whichcontains the character code, normalized by jQuery.The
keyuphandler is necessary to catch characters that are input using Ctrl-V (note that it unfortunately doesn’t catch input using the menu option Edit > Paste). The extra test is necessary to stop the input field from getting back to its most left position after everykeyup(caused by changing its value). Now it only resets its position when there is something to be removed.You can test it on JSBin.