I borrowed a bit of code from this question (see reply 4):
how do i block or restrict special characters from input fields with jquery?
However, upon using the code, it appears, that although it does the validation as you type neatly, it does not allow you to edit anything you have entered.
$('input').bind('keypress', function (event) {
var regex = new RegExp("^[a-zA-Z0-9]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}});
I am a bit confused, I have tried to adjust it by changing the keypress to keyup but this just stops the validation from working. Any pointers would be graciously accepted.
This seems to be a browser specific issue. In Firefox keypress includes meta keys like backspace and the arrow keys while Chrome does not. If you adjust your logic a bit to prefer which over charCode (which I think is better supported anyways) you end up with this
This fiddle also writes to console the keys and codes being passed in the event when typing.
http://jsfiddle.net/Q2MWS/5/