In this article I will explain with an example, how to restrict user from entering Special Characters in TextBox using JavaScript.
This article will illustrate how to perform AlphaNumeric validation for TextBox i.e. allow only Alphabets and Numbers in TextBox using JavaScript.
The script works in such a way that the Password TextBox will accept only alphabets, numbers i.e. AlphaNumeric values, thus unless a Special Character key has been specified to be excluded it won’t be accepted.
 
 
HTML Markup
The following HTML Markup consists of an HTML TextBox and an HTML SPAN. The HTML TextBox has been assigned an OnKeyPress event handler which makes call to a JavaScript function and the OnDrop and OnPaste events which have been cancelled by setting return false.
Alphanumeric value:
<input type="text" id="text1" onkeypress="return IsAlphaNumeric(event);" ondrop="return false;" onpaste="return false;" />
<span id="error" style="color: Red; display: none">* Special Characters not allowed.</span>
 
 
JavaScript function to restrict user from entering Special Characters in TextBox
Initially an Array is created which stores the ASCII Key Codes of all the allowed Special Characters.
Note: For more details on various Keyboard key ASCII code please visit Keyboard Keys and Key Code Values.
 
Inside the IsAlphaNumeric JavaScript function, first the KeyCode of the pressed Keyboard key is determined and then it is matched with the ASCII Key Codes values of
1. Uppercase Alphabets.
2. Lowercase Alphabets.
3. Numbers (Digits).
4. Special Keys inserted in the Array.
And only if the character matches any of the above then only it is allowed in the TextBox.
<script type="text/javascript">
     var specialKeys = new Array();
     specialKeys.push(8);  //Backspace
     specialKeys.push(9);  //Tab
     specialKeys.push(46); //Delete
     specialKeys.push(36); //Home
     specialKeys.push(35); //End
     specialKeys.push(37); //Left
     specialKeys.push(39); //Right
     
     function IsAlphaNumeric(e) {
         var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode;
         var ret = ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122) || (specialKeys.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode));
         document.getElementById("error").style.display = ret ? "none" : "inline";
         return ret;
     }
</script>
 
 
Screenshot
Restrict user from entering Special Characters in TextBox using JavaScript
 
 
Browser Compatibility

The above code has been tested in the following browsers.

Internet Explorer  FireFox  Chrome  Safari  Opera 

* All browser logos displayed above are property of their respective owners.

 
 
Demo
 
 
Downloads