In this short article I will explain how to validate email addresses client side using JavaScript with the help of Regular Expressions.
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<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("Invalid email address.");
}
else {
alert("Valid email address.");
}
}
</script>
</head>
<body>
<form id="form1">
<input type="text" id="txtEmail" />
<input type="button" id="btnValidate" value="Validate Email" onclick = "ValidateEmail()" />
</form>
</body>
</html>
Above you will notice when the button u>btnValidate is clicked, the email address entered in the HTML TextBox txtEmail is validated using Regular Expression. And based on whether the validation is successful or failed an alert message box is displayed.