In this article I will explain with an example, how to perform AlphaNumeric validation i.e. allow only Alphabets and Numbers using OnKeyPress event in JavaScript.
When User types in the TextBox, the text in the TextBox will be validated using OnKeyPress event handler in JavaScript and if the inputted character is not AlphaNumeric i.e. Alphabet or Number, the error message will be displayed next to the TextBox.
 
 
HTML Markup
The following HTML Markup consists of an HTML TextBox and a SPAN element. The TextBox has been assigned an OnKeyPress event handler which calls the Validate JavaScript function.
<input type="text" id="txtName" onkeypress="return Validate(event);" />
<span id="lblError" style="color: red"></span>
 
 
JavaScript function to perform AlphaNumeric validation using OnKeyPress event
When User types in the TextBox, the Validate JavaScript function will be called on the OnKeyPress event.
Inside the Validate JavaScript function, the Key code (ASCII code) of the character is validated against a Regular Expression (Regex) and if the entered character is not AlphaNumeric i.e. Alphabet or Number then the event is cancelled, the character is not entered in the TextBox and an error message is displayed next to the TextBox using JavaScript.
<script type="text/javascript">
    function Validate(e) {
        var keyCode = e.keyCode || e.which;
        var lblError = document.getElementById("lblError");
        lblError.innerHTML = "";
 
        //Regex for Valid Characters i.e. Alphabets and Numbers.
        var regex = /^[A-Za-z0-9]+$/;
 
        //Validate TextBox value against the Regex.
        var isValid = regex.test(String.fromCharCode(keyCode));
        if (!isValid) {
            lblError.innerHTML = "Only Alphabets and Numbers allowed.";
        }
 
        return isValid;
    }
</script>
 
 
Screenshot
Perform AlphaNumeric validation (Alphabets and Numbers) using OnKeyPress in 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