We want to keep users from entering special characters into our textbox input on or form. Ideally we want to not allow those characters to be entered at all, as opposed to let them enter the characters, check to see if they did, and then alerting them. Too much work, simply keep them from entering special characters from the beginning. For this we'll use JavaScript's onKeyPress event, which looks like this:
We'll construct a function that will check for special characters. And, well, here it is:
function isAlphaNum(event) {
var regex = new RegExp("^[a-zA-Z0-9\\s]+$");
//alert(event + ' - ' + regex);
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
}
A quick walk through of the code.... the function is called "isAlphaNum()". The regex we are checking against is "^[a-zA-Z0-9]+$", which checks for numbers and upper and lowercase letters. I wanted allow spaces too, so I added the "\\s" to make it "^[a-zA-Z0-9\\s]+$". The commented alert is for testing. The function checks to see if the keypress does NOT match the expression and returns false. It does nothing if it passes the regex test.
My final HTML form text box looks like:
Try it out! You will be unable to type in a character other than a number, letter or space.