Block Special Characters from a Text Box Form Input

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:

view plain print about
1<input type="text" onkeypress="myFunction()">

We'll construct a function that will check for special characters. And, well, here it is:

view plain print about
1function isAlphaNum(event) {
2 var regex = new RegExp("^[a-zA-Z0-9\\s]+$");
3 //alert(event + ' - ' + regex);
4 var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
5 if (!regex.test(key)) {
6 event.preventDefault();
7 return false;
8 }
9}

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:

view plain print about
1<input type="text" onkeypress="isAlphaNum(event);">

Try it out! You will be unable to type in a character other than a number, letter or space.

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
BlogCFC was created by Raymond Camden. This blog is running version 5.9.7. Contact Blog Owner