Home / Email Marketing / Check Email Address with JavaScript and Regular Expressions
rexpressions

Check Email Address with JavaScript and Regular Expressions

A while ago I put up a Password Strength Checker using JavaScript and Regular Expressions. On that same note, you can also check the structure of an email address utilizing the same regular expression (regex) methodology.

If your form element has the id=”emailaddress” and you add a form onSubmit=”return checkEmail();“, this is a Javascript function that you can utilize to return an alert if the email address has a valid structure or not:

<script language="javascript">
function checkEmail() {
var email = document.getElementById('emailaddress');
var filter = /^(([^<>()[]\.,;:s@"]+(.[^<>()[]\.,;:s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
}
</script>

The function validates the contents of the email to that of the filter. If the comparison fails, it pops up an alert and returns the focus back to the email address field!

About Douglas Karr

Douglas Karr is the founder of The Marketing Technology Blog. Doug is the CMO of CircuPress and CEO of DK New Media, an agency specializing in assisting marketing technology companies with their inbound marketing - leveraging social media, blogging, search engine optimization, pay per click and public relations. Their clients include Angie's List, GoDaddy, Mindjet and many more. Douglas is also the author of Corporate Blogging for Dummies.

Check Also

History of Email and Email Design

The History of Email and Email Design

44 years ago, Raymond Tomlinson was working on ARPANET (the U.S. Government’s precursor to the ...

41 comments

  1. For forms with multiple email addresses, it would be good to do class=”emailaddress”. If you have the prototype.js library (http://www.prototypejs.org) included on the page you can do something like this:

    var valid = true;
    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    $$(‘.emailaddress’).each( function(email) {
    if (!filter.test(email.value)) {
    alert(?Please provide a valid email address?);
    email.focus;
    valid = false;
    }
    });
    return valid;

  2. Nice, I can always count on you for some wicked cool scripts! :)

  3. I like the idea, but I would be hesitant to adopt this particular regular expression without description of which legal email addresses it does not accept and which illegal addresses it permits.

    For an example of a regular expression that does a decent job alongside an explanation of which cases it does not cover, see this:

    http://www.regular-expressions.info/email.html

    My personal preference is to cover most of the simple cases and issue a warning for everything else rather than rejecting it. If Bob really want sto submit bob@com.museum rather than bob@museum.com, why not let him?

    • Hi Reg,

      You can test out the Regex utilizing an Online Regex Tester.

      Also, there’s definitely much more that can be done if you want to ensure an email address is valid in accordance with the RFC.

      There are a few reasons not to allow someone to enter an invalid email address:
      1. They will get annoyed at you when the email they expected doesn’t get through – regardless of whether or not it was your fault the address was entered incorrectly.
      2. If com.museum was a valid domain and, let’s say, Yahoo! operated it – any email address that bounced would have a negative impact on your company’s reputation for email delivery. This could lead to all of your company’s email being blocked.
      3. If your email service provider allowed you to enter bob@com.museum, you’d also pay for each email sent to that email address until they unsubscribed that address due to bounces. I would steer clear of any ESP that would allow an invalid email address like that – they’re just taking your money!

      Thanks for stopping by!
      Doug

  4. Perfect, just what I needed!

  5. There’s much simpler way to write the expression:
    var regex = /^[a-z0-9\._-]+@([a-z0-9_-]+\.)+[a-z]{2,6}$/i;
    – With the final modifier /i there’s no need to indicate the upper case range.
    – I don’t know of any TLD with numbers in it.
    On a side note, I do allow TLD with up to 6 chars; new ones arrive regularly and you never know (well, somme future ones may even have numbers in it, I know).

  6. Hi there,

    I am tring to use this in an existing form in real-time, but this doesnt appear to be validating in realtime like your password strength checker…

    Or, am i just that clueless, and it aint workin for me?

  7. btw, I really like what you have going on here, your tutorials are very simple, I will definately be bookmarking this one….

  8. Just an FYI; I haven’t tried Ade’s solution but the pattern above doesn’t validate e-mail addresses with apostrophes in them.. (eg, Mike.O’Hare@Whatever.com). Apostrophes are valid per the RFC 2821/2822 –> http://www.faqs.org/rfcs/rfc2822.html

    HTH,
    Sanjay

  9. Would be fine if we could find a solution to avoid fake e-mail addresses on comments on WordPress

  10. Just a small correction: The regular expression has an extra ()+ at the end. It should read:

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

    With the first one any length TLDs would be accepted (which is not intrinsecally wrong as others have pointed out, but if that was the intention the expression could be shortened).

  11. Can you please explain the regular expression of this code and how its working? Also about .test – Is .test a default statement in javascript to check things like you did in the code above?

  12. This is a short code for email expression-

    function validateEmail(id)
    {
    var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/;
    return emailPattern.test(id);

    }
    Deepak Rai
    varanasi

  13. This is a short code for email expression-

    function validateEmail(id)
    {
    var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/;
    return emailPattern.test(id);

    }
    Deepak Rai
    varanasi

  14. Thanks a lot uncle. That helped me a lot :)

    Amanda

  15. Thanks, but there is an error in this regex. I'm not a regex expert, but I tried email:

    test@test

    and it passed the regex… I noticed it's lacking escaping the "." so it should be:

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

  16. Im rolling with

    /^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$/

  17. Well, this is just a rough check but not 100% accurate, for example this would be okay with john_doe.@gmail.com which is actually not a valid e-mail address (dot is not allowed as a last character in local part of e-mail).
    Also it would accept john…doe@gmail.com which is also invalid since there cannot be more than one dot in a sequence.

    These are just some flaws I noticed at the first sight.
    My intention is not bashing just to point this out in case someone is planning to use this as a security check – not secure enough.

    For info about valid e-mail addresses check this out: http://en.wikipedia.org/wiki/E-mail_address

  18. Deepak,

    Actually, I think you need to apply a escape for the dot (“.”). So , your function should be, instead:

    function validateEmail(id)
    {
    var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/;
    return emailPattern.test(id);

    }

    Otherwise, the dot would mean “any character”. I believe such special characters need to be escaped.

    Regards,

    Federico

  19. function validateEmail(fld) {
    var error=””;
    var tfld = trim(fld.value); // value of field with whitespace trimmed off
    var emailFilter = /^[^@]+@[^@.]+.[^@]*ww$/ ;
    var illegalChars= /[(),;:\”[]]/ ;

    if (fld.value == “Enter your email Address”) {

    error = “Please enter your Email address.n”;
    } else if (!emailFilter.test(tfld)) { //test email for illegal characters

    error = “Please enter a valid email address.n”;
    } else if (fld.value.match(illegalChars)) {

    error = “Please enter a valid email address.n”;
    }
    return error;
    }

  20. function validateEmail(fld) {
    var error=””;
    var tfld = trim(fld.value); // value of field with whitespace trimmed off
    var emailFilter = /^[^@]+@[^@.]+.[^@]*ww$/ ;
    var illegalChars= /[(),;:\”[]]/ ;

    if (fld.value == “Enter your email Address”) {

    error = “Please enter your Email address.n”;
    } else if (!emailFilter.test(tfld)) { //test email for illegal characters

    error = “Please enter a valid email address.n”;
    } else if (fld.value.match(illegalChars)) {

    error = “Please enter a valid email address.n”;
    }
    return error;
    }

  21. function validateEmail(fld) {
    var error=””;
    var tfld = trim(fld.value); // value of field with whitespace trimmed off
    var emailFilter = /^[^@]+@[^@.]+.[^@]*ww$/ ;
    var illegalChars= /[(),;:\”[]]/ ;

    if (fld.value == “Enter your email Address”) {

    error = “Please enter your Email address.n”;
    } else if (!emailFilter.test(tfld)) { //test email for illegal characters

    error = “Please enter a valid email address.n”;
    } else if (fld.value.match(illegalChars)) {

    error = “Please enter a valid email address.n”;
    }
    return error;
    }

  22. function validateEmail(fld) {
    var error=””;
    var tfld = trim(fld.value); // value of field with whitespace trimmed off
    var emailFilter = /^[^@]+@[^@.]+.[^@]*ww$/ ;
    var illegalChars= /[(),;:\”[]]/ ;

    if (fld.value == “Enter your email Address”) {

    error = “Please enter your Email address.n”;
    } else if (!emailFilter.test(tfld)) { //test email for illegal characters

    error = “Please enter a valid email address.n”;
    } else if (fld.value.match(illegalChars)) {

    error = “Please enter a valid email address.n”;
    }
    return error;
    }

  23. function trim(s)
    {
    return s.replace(/^s+|s+$/, ”);
    }

  24. function trim(s)
    {
    return s.replace(/^s+|s+$/, ”);
    }

  25. The ‘.focus’ is a function, it should be:

    email.focus()

  26. The ‘.focus’ is a function, it should be:

    email.focus()

  27. Works like gem.. Great use of reg expressions in javascript…

  28. It´s a crack in the gem…
    The address “mmm@mmm..com” will be accepted. But two dots together is not valid.
     

  29. Fellas, use . It does not require any JS validation.

Leave a Reply