Last month I wrote about regular expressions in Java, today I’ll show you how to use regular expression in JavaScript to validate email address.
Here is the code to validate email address in JavaScript using regular expression.
function validateEmail(elementValue){
var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
return emailPattern.test(elementValue);
}
Explanation:
The argument to this method is the email address you want to validate.
In the method body we define a variable (‘emailPattern’) and assign a regular expression to it.
/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/
To understand the regular expression we will divide it into smaller components:
/^[a-zA-Z0-9._-]+: Means that the email address must begin with alpha-numeric characters (both lowercase and uppercase characters are allowed). It may have periods,underscores and hyphens.
@: There must be a ‘@’ symbol after initial characters.
[a-zA-Z0-9.-]+: After the ‘@’ sign there must be some alpha-numeric characters. It can also contain period (‘.’) and and hyphens(‘-’).
\.: After the second group of characters there must be a period (‘.’). This is to separate domain and subdomain names.
[a-zA-Z]{2,4}$/: Finally, the email address must end with two to four alphabets. Having a-z and A-Z means that both lowercase and uppercase letters are allowed.
{2,4} indicates the minimum and maximum number of characters. This will allow domain names with 2, 3 and 4 characters e.g.; us, tx, org, com, net, wxyz).
On the final line we call test method for our regular expression and pass the email address as input. If the input email address satisfies our regular expression, ‘test’ will return true otherwise it will return false. We return this value to the calling method.
You can call this method whenever you want to validate email address.
Popularity: 100% [?]
If you enjoyed this post, make sure you subscribe to my RSS feed!Related posts:
- Ultimate Java Regular Expression to validate any email address.
- Validate Zip code using JavaScript Regular expression
- Validate U.S Phone Numbers using JavaScript Regular expression.
- How to validate email, SSN, phone number in Java using Regular expressions.
- How to validate Social Security Number (SSN) using JavaScript Regular Expressions






Hey, nice useful piece of code. Always nice to find something that takes a fairly common task, such as email validation, and breaks down the logic and provides a simple piece of code in the end.
Bret, I am glad you liked this post. Thanks for visiting.
hey, nice explanation, its helped me allott.
Hi , email validation code present in this site is very nice and it is very useful to validate email address using regular expressions. My sincere thanks to the programmer who posted this. This help me alot.
Thanks & Regards,
Latha
Latha, I am glad that you found this post helpful. I appreciate your comments.
Hi can anyone help me how to invalidate the session , when i am clicking LOGOUT button. I use session.invalidate() method , the page has been expired. But when click back button on browser it goes to back page. How to avoid this. I request you any body can solve this problem.
yours
Latha
Hi,
Very nice one which helped me a lot.
I tried the below code for checking alphabets, hyphen and underscore. However its not working.
Could any of you help me on this.
function validateChars(elementValue)
{
var charsPattern = /[a-zA-Z0-9_-]*/;
return charsPattern.test(elementValue);
}
Thanks.
Thanks for this. Saved me some work.
There is a small error in the regexp: top-level domains could be longer than 4 characters (like .travel and .museum).
dfd
Don’t you need to escape the period? ie:
[a-zA-Z0-9._-]
should be:
[a-zA-Z0-9\._-]
Otherwise, isn’t a period a single character wildcard?
And can’t a-zA-Z0-9 be replaced with \\w?
ps Should also add apostrophe ‘ for Irish names, that’s the reason I was hunting this stuff down!
Hi,
Thank you very much for this article. It helps me for achieving my form. In addition, your explanation is clear and light.
Josue, I am glad that you found this post useful.
Good Job – really easy to understand explanation
Hey Mike,
[a-zA-Z0-9_] can be replaced with \w.
also, because the . is included in the second character class(after @), this would be considered a valid email:
a@a…….com
not sure what the solution to that is. .
\.{1} does limit the repetition of . to one, but since the previous characters have already been passed, the limiter becomes irrelevant.
anyone?
Hi Zaheer,
Really clever solution, using regular expressions for validations.
I am studing at uni and we covered regular expressions on our
Unix system programing course. I see the usefulness of regular expressions now !
Keep posting more tips
Cheers,
Armando
.@..ww
is a valid email address?
thanks
Not that I’m totally impressed, but this is more than I expected for when I found a link on SU telling that the info here is quite decent. Thanks.
Validate email address using regular expressions, nice piece of work. Very simple and clean. Thanks for the code. Helps me a lot.
– Jim
This pattern isn’t a good for e-mail addresses. This pattern will filter out few of the WELL-FORMED e-mails and of MAL-FORMED as well.
gonzo: that is quite an unfounded statement. could you please give examples of both. and if you are so smart, could you show solutions also? (there is already a comment showing it accepts faulty emails)
I too found that this regex has some flaws. An email like asdf@asdf would pass the filter. It doesn’t check for the .tld.
The guys at http://www.4guysfromrolla.com/webtech/052899-1.shtml have offered this, which ensures there’s a .tld :
^[\\w-_\.+]*[\\w-_\.]\@([\\w]+\\.)+[\\w]+[\\w]$
I would encourage everyone to learn RegEx, it’s invaluable when you have to manipulate data, and who doesn’t these days. Zaheer’s lesson still teaches a lot.
@Mike VandeVelde
I believe apostrophes are illegal characters in emails.
based on the above I think that:
/^[\w.+-]+@[\w.-]+\.[a-z]{2,6}$/i
might be a better solution.
\w to match alphanumeric characters and underscores
i on the end to be case insensitive
{2,6} rather than {2,4} to cope with .museum
this still doesn’t address .@..ww or similar though.
/^((\w+\+*\-*)+\.?)+@((\w+\+*\-*)+\.?)*[\w-]+\.[a-z]{2,6}$/i
Should deal with that problem though (I have not tested this fully but it works on those that I have tested which it should work on and catches those that are invalid which I tried)
(\w+\+*\-*) matches an more than one alphanumeric followed by zero or more +s and zero or more -s
(\w+\+*\-*)+ matches this happening at least once.
((\w+\+*\-*)+\.?)+ matches this happening at least once with or without a . afterwards
((\w+\+*\-*)+\.?)* is the same except that it matches 0 or more times.
[\w-]+ matches at least 1 alphanumeric character or hyphen.
I hope this helps people.
Daniel wrote:
/^((\w+\+*\-*)+\.?)+@((\w+\+*\-*)+\.?)*[\w-]+\.[a-z]{2,6}$/i
Nice one!
I tested it with something like:
x test
x test..@..com
x test..@example..com
x test..@example.example.com
x test.2@example.com.
v test.2@example.example.com
(x fails, v passes)
I used to have a script of my own that worked really nice (apart from 6-char TLD), but was about 45 lines of code…
Zaheer and Daniel: Thank you for this huge improvement
In the above test.@test.com is pass, also numerics / _ are allowed to start the email address, below regex works fine to some extent.
/^[a-zA-Z]([a-zA-Z0-9-_])*(\.[a-zA-Z0-9-_])*@[a-zA-Z0-9](([a-zA-Z0-9\-\_\.])*)+\.[a-zA-Z]{2,4}$/
Thanks and congratulations to Zaheer for this article: It is very well written and it is easy to read. Thanks also to the rest of people who contributed to enhance this code.
I would like to share with you the following regex that I tried with all samples shown before (and some more, of course). I think it is worth a try:
^([A-Za-z0-9]{1,}([-_\.&'][A-Za-z0-9]{1,}){0,}){1,}@(([A-Za-z0-9]{1,}[-]{0,1})\.){1,}[A-Za-z]{2,6}$
I think this pretty well matches a great number of e-mail addresses.
Regards,
Francisco.
Hai Latha,
I know its a very late reply for the question which you’ve asked. Anyway let it help the users who view this forum.
Your Question:
“Hi can anyone help me how to invalidate the session , when i am clicking LOGOUT button. I use session.invalidate() method , the page has been expired. But when click back button on browser it goes to back page. How to avoid this. I request you any body can solve this problem.”
Answer:
response.setHeader(“Cache-Control”,”no-cache,no-store”);
response.setDateHeader(“Expires”, 0);
response.setHeader(“Pragma”,”no-cache”);
just try to add the above code and check.
That helped me a lot!!
THANK YOU!!
good one..!
Thanks ashish.
Are mail-adresses with more than one “@” okay?
I was just wondering. Many of the regexp allow more than one “@”. Nevertheless some regexp allow combinations like test@test@example.org ….
Fabian, I have not seen any email address with multiple ‘@’ symbol and I believe that would be illegal. An email address should have at most one @.
All exp failing at test:
test@example..org
Any solns for it ?
Nice Post it will helps lot ,
How can we handle multiple email’s by using comma separated.
any solution for (a@gmail.com,b@yahoo.co.in,c@gmail.com)
Hi All,
am using this exp”" /^[a-zA-Z0-9\._%-]+@[A-Z0-9\.-]+\.[A-Z]{2,4}(?:(?:[,][A-Z0-9\._%-]+@[A-Z0-9\.-]+))?$/i “”
it’s handling this format very fine a@gmail.com,b@yahoo.co.in , while come to a@gmail.com,b@yahoo.co.in,c@gmail.com not working.
plz help me for this req
This is just what I was looking for, thanks very much!
Thanks. This RegEx pattern saved my day.
Thanks to u Very Good Explanation of Regular Expressions
askkuber.com TEam
@Bhushna for you : /^[a-zA-Z0-9\._%-]+@[A-Z0-9\.-]+\.[a-zA-Z]{2,4}(?:(?:[,][a-zA-Z0-9\._%-]+@[a-zA-Z0-9\.-]+))?$/i
Actually if you read the relevant RFCs, pretty much any character is technically valid before the final ‘@’ sign (at least in escaped or quoted sections) – the format of that part is left completely to the receiving mail server to interpret (“Abc@def”@example.com is valid, for example). The part after the ‘@’ sign is more restrictive, because only certain characters can be used in domain names.
You should certainly support apostrophes before the ‘@’, all but one of these regexes suggested will fail on valid email addresses like
jim.o’neill@example.com