
How to write JavaScript regex validation for email?

<html>
<head>
<title>Email validation using regex</title>
<script type="text/javascript">
function validate() {
var email = document.getElementById("email").value;
var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if (emailPattern.test(email)) {
alert("Email Id: " + email);
return true;
} else {
alert("Email Id is not valid!");
return false;
}
}
</script>
</head>
<body>
<h2>Validating Email Id..</h2>
Email Id :
<input type="text" name="email" id="email" />
<input type="submit" value="Submit" onclick="validate();"/>
</body>
</html>

Email pattern is like HYPERLINK "mailto:abc@ab.aaa" abc@ab.aaa. you have to check the pattern of combination of these two. Sometimes space is also included in it. In pattern /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/ /../(forward slashes) is used to quote your regular expression. ^ shows beginning of string. [..] matches any letter enclosed with in. + shows that preceding character come 1 or more times. . Shows that \ will treat . as a literal. {2,4} shows the range that content having length between 2 to 4. $ is used for ending the string. test() method takes one argument and check that to the pattern.

Don't forget that some TLDs are longer than 4 characters, for example .museum. I've used a 7 character length for TLD and you can see it in action at