Validating an email via JavaScript

Nearly every programmer needs to validate email id somewhere sometime while development. Here I have got a simple regex that is very good at validating JavaScript.

Demo

Email



Here is the plain HTML of the demo.

1
2
Email<input id="testemail" type="text" name="testemail" />
<button onclick="javascript: check_it();" type="button">Check email</button>

The button on the third line does the calling to the function I have setup to validate the email id. Remember that this is just client-side verification of the email id.

Here is the plain script.

1
2
3
4
5
6
7
8
9
10
11
<script type="text/javascript">
function check_it() {
	var emailid= document.getElementById('testemail').value;
	var regular_mail = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (!regular_mail.test(emailid)) {
		alert("Invalid email id");
	} else {
		alert("Valid email id");
	}
}
</script>

The regex script in line 4 is all we need to validate the email id.

The current regex can be modified as per use. Say if you want to make it case sensitive, you can do it like this.

1
2
3
4
5
Original regex
/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/
 
Modified regex
/^[A-Z0-9._%+-][email protected][A-Z0-9.-]+\.[A-Z]{2,4}$/i;

 

Here is the breakdown of the regex to explain its working:

^ = Matches the beginning of the string.

([a-zA-Z0-9_\.\-]) or [A-Z0-9._%+-] = Bracket expression that will match any small letter(a-z), any capital letter(A-Z), any number (0-9), dot (.), underscore (_), percent sign (%), plus(+) and minus (-).

+ = This will match the preceding element, in this case the bracket expression, 1 or more times. In summary the bracket expression with the (+) will match a person’s email alias.

@ = Match the (@) symbol in the email address.

([a-zA-Z0-9\-]) or [A-Z0-9.-] = Bracket expression that will match any letter(a-z) or (A-Z), any number (0-9), dot (.), and minus (-).

+ = This will match the preceding element, in this case the bracket expression, 1 or more times.

\. = The dot (.) in this case is matched and it is escaped with the backslash (\) because the dot by itself is used to match any single character when used in a regex (when it is outside of a bracket expression).

[a-zA-Z0-9] or [A-Z] = Bracket expression that will match any letter or number(a-zA-Z0-9) or just (A-Z).

{2,4} = Matches the preceding element at least 2 times and not more than 4 times. In summary the bracket expression with the ({2,4}) will match the top-level domain name such as com, net, or info.

Good luck.

Leave a Reply