Validate email address using JavaScript regular expression

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.

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

150 Thoughts on “Validate email address using JavaScript regular expression

  1. Asslam-u-Alaikum,
    Very Informative and Helpful code. specially learners and beginners.

    Wasalam

  2. Andrea on April 9, 2012 at 12:41 am said:

    Thanks everyone for your contributions.
    I went with Tank’s solution and Kent’s modification. Does the trick for me!~

  3. I’m using this and it’s working perfect:

    mailRegex = /[a-z0-9!#$%&’*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&’*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])/;

    This will help you validating wrong emails including: name@sample..com

    Best Regards,
    Mohamed

  4. Darryl Young on April 17, 2012 at 8:38 am said:

    Hey,

    I’m glad I came across this thread and I hope I can get some help off you guys! I’m trying to work with an previously written JavaScript function to validate an email but it’s having problems if the user enters a space at the end of their email address (it happens, especially on mobile with auto-complete etc). How could I amend the following code to allow a space at the end?

    function checkMail(emailInput) {
    filter = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    if(!filter.test(document.lpform.email.value)) {
    $(“#email”).addClass(“error”).focus();
    $(“#email”).blur();
    document.getElementById(‘dataStatus’).style.display=”block”;
    return false; }
    return true;
    }

    Thanks so much! I really appreciate it. =D

  5. Darryl Young on April 19, 2012 at 4:56 am said:

    Ok, I just added \s and that worked…

    filter = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z\s]{2,4}$/;

    Thanks anyway.

  6. John on May 1, 2012 at 8:19 am said:

    Hello All,

    I am Glad that i have landed to this email. I have a new requirement for validating email for a new format, can anyone tell me how to by pass.

    Contact350test/Vendor@ab.com

    I tried removing / from the below exemplist, But the code is throwing JS error.

    var exemplist =/^[a-zA-Z][\w\.-]*[a-zA-Z0-9]*@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/

    Thanks in advance.

  7. very nice content it is very useful to me.

  8. fgsdf gsdfg

  9. cvcvbcvb cv b

  10. Lúcia Ribeiro on June 19, 2012 at 11:55 pm said:

    I neead to receio my email

  11. Lúcia Ribeiro on June 19, 2012 at 11:57 pm said:

    I
    Med.

  12. Lúcia Ribeiro on June 19, 2012 at 11:59 pm said:

    Thanks

  13. Lúcia Ribeiro on June 20, 2012 at 12:00 am said:

    I breaste

  14. Meesam Akhtar on July 4, 2012 at 1:24 am said:

    Valid email-id for all different kinds of email-ids(e.g. meesam.akhtar@domain.com OR meesam.akhtar@domain.co.in OR meesam.akhtar@domain.travel.uk.

    Regular expression for Email-Id– /^([a-zA-Z0-9_\-])+\@(([a-zA-Z0-9\-])+)+(\.[a-zA-Z]{2,6})(\.[a-zA-Z]{2})?$/i

  15. Dennis on July 16, 2012 at 1:32 am said:

    @John I hope i’m not too late to answer you. Try this

    /^(([a-zA-Z0-9._-])||([a-zA-Z0-9._-]+\/))+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/

    to bypass this Contact350test/Vendor@ab.com.

  16. ramesh on July 17, 2012 at 5:19 am said:

    very nice..easy to learn or do…

  17. Pity that this does not take account with emails like initials.lastname@student.college.com

  18. Great dude 😀 we were looking for the regular expressions explanation since long. 😀 Thanx a ton

  19. karim on April 22, 2013 at 1:47 am said:

    this is gud

  20. Thank you for your regexp, it really works!

  21. Eduardo Neto on October 31, 2013 at 5:09 pm said:

    thank you guy!

  22. Even g?ing ove? budget sl?ghtly to get the sttyle
    of lights t??t ?ou want caan leave you feeling l?ke the projected wasn’t completed as t?ough you wanteed ?t.

    The se?ond reasons w?y solar Christmas lights
    shoul? ?? u?ed is t?at t?ey are rel?tively safer than th? traditional
    Christmas lights. Youu ?ill ?? cleaning t?em ?uring the day ?o thdre i? no need for them to b? on and
    you don’t ?ant to damage the lights or electrocute yoursekf ?n the
    process.

  23. As has been stated, medical insurance is a thing that could be a very serious matter.
    Usually, PPOs cost more than traditional HMOs,but offer more options
    to their members. The majority off people invest in companies that provide cheap
    insurance quotes.

  24. Greate pieces. Keep writing such kind of info on your
    blog. Im really impressed by your site.
    Hello there, You have performed an excellent job.
    I will certainly digg it and for my part recommend to my friends.

    I am confident they’ll be benefited from this web site.

  25. Asde from video games, the event also focuses on anime and manga products.
    If you’re reading this article, it means you’re interested in
    downloading soime free Android games- start with tthis
    one. The clitoris’ shape actully resembles the penis, except for its body is not outside
    but insdide unnder the so-called hood.

  26. Wow, that’s what I was seeking for, what a information!
    present here at this webpage, thanks admin of this
    web site.

    Visit my site; Psn Code

  27. how much does a mental health counselor make [url=http://www.rgdmape.com/fiere/cytotec.html]cytotec[/url] mercy general health partners

  28. Incredible! This blog looks just like my old one!

    It’s on a totally different subject but it has pretty
    much the same layout and design. Outstanding choice of colors!

    Also visit my web-site :: hungry shark evolution hack

  29. I’m not sure why but this blog is loading incredibly slow for
    me. Is anyone else having this issue or is it a issue on my end?
    I’ll check back later on and see if the problem
    still exists.

    Also visit my web site: wizard101 crown Generator

  30. Hurrah, that’s what I was seeking for, wht a material!
    existing here at this webpage, thanks admin of this webb site.

  31. You should nevertheless forever be all aware of the fact
    that utilising a rifle is a large obligation and thast it shoulld in no situation be
    used for the wrong things, neither aginst family nor against animate beings or lesser
    beings. This “A Christmas Story” quote is a narration from older Ralphie.
    The very first medal India received at the Olympic Games came
    from Gagan Narang, a shooter who won the bronze medal, also known as the third prize, in the men’s 10 m aiir rifle event.

  32. Thanks for some other excellent post. The place else may just anyone get that kind of information in such an ideal
    means of writing? I have a presentation next week, and I’m on the look for such
    information.

  33. I enjoy what you guys are usually up too. This sort of clever
    work and reporting! Keep up the superb works guys I’ve incorporated you guys to our blogroll.

  34. I write a comment when I appreciate a article on a site or if I have
    something to valuable to contribute to the discussion. Usually it
    is a result of the passion communicated in the article I browsed.
    And after this article Validate email address using JavaScript regular expression. I was actually excited enough to
    leave a thought 🙂 I do have 2 questions for you if you usually do not
    mind. Is it just me or does it appear like a few of these remarks come across
    as if they are written by brain dead folks? 😛 And, if you
    are posting at other sites, I’d like to keep up with everything new you have to post.
    Would you list every one of your community pages like your Facebook page, twitter feed,
    or linkedin profile?

  35. Soon the drugs you use are not enough and you need more
    and more. Get auto insurance quotes [nxy.in] for low income and
    you will find that there are policies in the market that
    have low rates. A rising number of countries in the world today have
    made it compulsory for an automobile to be insured at the time of
    purchase.

  36. What’s up i am kavin, its my first occasion to commenting anywhere,
    when i read this paragraph i thought i could also make comment due to this good
    piece of writing.

  37. With havin so much written content do you ever run into any issues of plagorism or copyright infringement?
    My website has a lot of completely unique content I’ve
    either authored myself or outsourced but it looks like a
    lot of it is popping it up all over the internet
    without my authorization. Do you know any methods
    to help prevent content from being ripped off? I’d definitely
    appreciate it.

  38. Had been actually searching for just an average shower enclosures before
    I uncovered this site, did not have any idea there were such
    a thing as a ‘steam shower enclosure’, really, might possibly just may have to have one

    Feel free to visit my homepage; steam sauna shower
    units [danlynch.org]

  39. Most protein shakes are loaded with sugar, fat, and other ingredients that
    aren’t even necessary for the body. If you want
    to build a considerable business, you’ll have to be able to come up with constant leads.

    7 million which was up $ 110 million compared to the year previous.

  40. Very rapidly this web page will be famous among all blogging and site-building people, due to it’s
    good articles oor reviews

  41. If this is important to you, make sure that the web video hosting service you choose to use offers these features.
    There are three different messages that can be chosen for St.
    ” Hopefully and follow-up interviews can get the public’s opinion.

  42. ERTERT on March 24, 2015 at 9:08 am said:

    VERY HELPFUL

  43. For case in point, exercise routines like push-ups do the job the triceps,
    biceps, chest, back, shoulders and even the abs which provides you a plethora of muscle mass targets to
    do the job on. Persistence is key. The basic nature of this festival is totally commercial
    and usually experience mass attendance with great pomp and show.

  44. Satyapriy on September 8, 2015 at 12:26 pm said:

    Very much useful… Lot many thanks…
    Keep helping…

  45. クールな情報の仕事を維持します!ありがとうは、巨大なポストを

  46. クサノオウのエリート主義のシャッフルボードheadaのjhelisaはaukinのtrubus義務

  47. It’s an remarkable post designed for all the online people; they will obtain advantage from it I am sure.

  48. Alex Meraz on February 8, 2016 at 12:23 pm said:

    Hola

  49. On the subject of digital advertising training, some firms are unique in it.
    Other instructional institutes, with a purpose to sustain and supply
    increasingly more online courses, have created quite a few training applications in the space of digital advertising and marketing.

  50. Remarkable! Its truly awesome post, I have got
    much clear idea concerning from this paragraph.

Comment navigation

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Post Navigation