In this article I will explain with an example, how to perform Email validation using OnKeyPress event in JavaScript.
The OnKeyPress event does not update the value of the TextBox when accessed using JavaScript and hence OnKeyUp event handler will be used to validate Email Address dynamically when User types in the Email Address in the TextBox.
 
 
HTML Markup
The following HTML Markup consists of an HTML TextBox and a SPAN element. The TextBox has been assigned an OnKeyUp event handler which calls the ValidateEmail JavaScript function.
<input type="text" id="txtEmail" onkeyup="ValidateEmail();" />
<span id="lblError" style="color: red"></span>
 
 
JavaScript function to perform Email validation OnKeyPress using JavaScript
When User types in the TextBox, the Email Address in the TextBox will be validated using OnKeyUp event handler in JavaScript and if the Email Address is invalid, the error message will be displayed next to the TextBox.
<script type="text/javascript">
    function ValidateEmail() {
        var email = document.getElementById("txtEmail").value;
        var lblError = document.getElementById("lblError");
        lblError.innerHTML = "";
        var expr = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
        if (!expr.test(email)) {
            lblError.innerHTML = "Invalid email address.";
        }
    }
</script>
 
 
Screenshot
Perform Email validation 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