In this article I will explain with an example, how to allow only AlphaNumeric character values i.e. Alphabets and Numbers with Space character in TextBox using JavaScript.
The script works in such a way that the TextBox will accept only alphabets, numbers i.e. alphanumeric values with space character, thus unless a special character key has been specified to be excluded it won’t be accepted.
You might also like to read:
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 allow only AlphaNumeric (Alphabets and Numbers) characters and space in TextBox
Initially an Array is created which stores the ASCII Key Codes of all the allowed Special Characters.
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. Space character.
5. 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 == 32 || (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
Browser Compatibility
The above code has been tested in the following browsers.
* All browser logos displayed above are property of their respective owners.
Demo
Downloads