zParacha.com

Effective programming and blogging tips by Zaheer Paracha

Subscribe:

-->
Posted by Zaheer 45 COMMENTS

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.

Email format: The regular expression for email is

/^[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.

Bookmark and Share

Popularity: 100% [?]

If you enjoyed this post, make sure you subscribe to my RSS feed!

Related posts:

categories: Javascript

45 Responses

  1. Bret says:

    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.

  2. zparacha says:

    Bret, I am glad you liked this post. Thanks for visiting.

  3. Mastan Jhoni says:

    hey, nice explanation, its helped me allott.

  4. Latha p says:

    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

  5. Zaheer says:

    Latha, I am glad that you found this post helpful. I appreciate your comments.

  6. Latha says:

    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

  7. Swaroop says:

    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.

  8. Blaise Kal says:

    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).

  9. 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!

  10. Josue says:

    Hi,
    Thank you very much for this article. It helps me for achieving my form. In addition, your explanation is clear and light.

  11. Zaheer says:

    Josue, I am glad that you found this post useful.

  12. Dario says:

    Good Job – really easy to understand explanation

  13. ray sweeten says:

    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?

  14. Armando says:

    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

  15. Matt says:

    .@..ww
    is a valid email address?

  16. Rossati Giovanni says:

    thanks

  17. 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.

  18. Jim says:

    Validate email address using regular expressions, nice piece of work. Very simple and clean. Thanks for the code. Helps me a lot.

    – Jim

  19. Gonzo says:

    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.

  20. mr disparate says:

    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)

  21. Martin says:

    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.

  22. Daniel says:

    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.

  23. Chasalin says:

    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 ;)

  24. Banu Channakeshava says:

    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}$/

  25. Francisco Parada says:

    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.

  26. Ajan says:

    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.

  27. Madhu says:

    That helped me a lot!!
    THANK YOU!!

  28. ashish says:

    good one..!

  29. Fabian says:

    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 ….

  30. 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 @.

  31. All exp failing at test:

    test@example..org

    Any solns for it ?

  32. Bhushna says:

    Nice Post it will helps lot ,

    How can we handle multiple email’s by using comma separated.

  33. Bhushna says:

    any solution for (a@gmail.com,b@yahoo.co.in,c@gmail.com)

  34. Bhushna says:

    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

  35. Tom Walters says:

    This is just what I was looking for, thanks very much!

  36. Dinesh says:

    Thanks. This RegEx pattern saved my day.

  37. askkuber says:

    Thanks to u Very Good Explanation of Regular Expressions

    askkuber.com TEam

  38. KrayoN says:

    @Bhushna for you : /^[a-zA-Z0-9\._%-]+@[A-Z0-9\.-]+\.[a-zA-Z]{2,4}(?:(?:[,][a-zA-Z0-9\._%-]+@[a-zA-Z0-9\.-]+))?$/i

  39. Michael says:

    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

Leave a Reply

Search

Sponsors

Get Adobe Flash playerPlugin by wpburn.com wordpress themes