HTML Markup
The HTML Markup consists of following elements:
TextBox – For entering email address.
Button – For validating the email address.
The Button has been assigned with a
JavaScript onclick event handler.
Email Address:
<input type="text" id="txtEmail" />
<br /><br />
<input type="button" id="btnValidate" value="Validate Email" onclick="ValidateEmail()" />
Validating Email Address in JavaScript using Regular Expressions
ValidateEmail
When the
Validate Button is clicked, the
ValidateEmail JavaScript function is called.
IsValidEmail
Inside the
IsValidEmail JavaScript function, email entered in the TextBox is passed as parameter and it is validated against the
Regular Expressions using test method and the validation status is returned i.e. TRUE or FALSE.
Finally, based on the validation an appropriate message is displayed using
JavaScript Alert Message box.
<script type="text/javascript">
function IsValidEmail(email) {
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})(\]?)$/;
return expr.test(email);
};
function ValidateEmail() {
var email = document.getElementById("txtEmail").value;
if (IsValidEmail(email)) {
alert("Valid email address.");
}
else {
alert("Invalid email address.");
}
}
</script>
Screenshot
Demo
Downloads