In this article I will explain with an example, how to perform simple Email validation using JavaScript.
The value of the Email TextBox will be validated with the help of Regular Expressions in JavaScript.
Validate multiple Email Addresses using JavaScript and Regular Expressions
The following HTML Markup consists of three HTML TextBoxes and an HTML Button. The three TextBoxes are assigned a common CSS class named email and the Button has been assigned a JavaScript Click event handler.
When the Button is clicked the ValidateEmails JavaScript method is executed.
Inside the ValidateEmails JavaScript method, a loop is executed over all the HTML TextBoxes and if the TextBox has the CSS class email then it is value is validated using the IsValidEmail JavaScript method which validates Email Address using Regular Expression.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<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 ValidateEmails() {
var message = ""
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "text" && inputs[i].className.indexOf("email") != -1) {
var email = inputs[i].value;
if (IsValidEmail(email)) {
message += email + " - Valid Email.\n"
} else {
message += email + " - Invalid Email.\n"
}
}
}
alert(message);
}
</script>
</head>
<body>
<form id="form1">
Email1: <input type="text" id="txtEmail1" class = "email" /><br />
Email2: <input type="text" id="txtEmail2" class = "email" /><br />
Email3: <input type="text" id="txtEmail3" class = "email" /><br />
<br />
<input type="button" id="btnValidate" value="Validate Email" onclick="ValidateEmails()" />
</form>
</body>
</html>
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