Monday, June 4, 2012

Validate email address in Javascript?


How can an email address be validated in Javascript?



Though this solution may be simple, I'm sure this is one of those useful things that people will be Googling for and deserves its own entry on the site



Source: Tips4all

18 comments:

  1. Using Regular Expressions is probably the best way. Here's an example (live demo):

    function validateEmail(email) {
    var re = /^(([^<>()[\]\\.,;:\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,}))$/;
    return re.test(email);
    }


    But keep in mind that one should not rely only upon JavaScript validation. JavaScript can easily be disabled. This should be validated on the server side as well.

    ReplyDelete
  2. There's something you have to understand the second you decide to use a regular expression to validate emails: It's probably not a good idea. Once you have come to terms with that, there are many implementations out there that can get you halfway there, this article sums them up nicely.

    In short, however, the only way to be absolutely, positively sure that what the user entered is in fact an email is to actually send an email and see what happens. Other than that it's all just guesses.

    ReplyDelete
  3. Just for completeness, here you have another RFC 2822 compliant regex


    The official standard is known as RFC 2822. It describes the syntax that valid email addresses must adhere to. You can (but you shouldn't — read on) implement it with this regular expression:

    (?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])


    (...) We get a more practical implementation of RFC 2822 if we omit the syntax using double quotes and square brackets. It will still match 99.99% of all email addresses in actual use today.

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


    A further change you could make is to allow any two-letter country code top level domain, and only specific generic top level domains. This regex filters dummy email addresses like asdf@adsf.adsf. You will need to update it as new top-level domains are added.

    [a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum)\b


    So even when following official standards, there are still trade-offs to be made. Don't blindly copy regular expressions from online libraries or discussion forums. Always test them on your own data and with your own applications.


    * Emphasis mine

    ReplyDelete
  4. Wow, lots of complexity here, if all you want to do is just catch the most obvious syntax errors, I would do something like this:

    \S+@\S+

    It usually catches the most obvious errors that the user makes and assures that the form is mostly right, which is what javascript validation is all about.

    ReplyDelete
  5. javascript can match regex:

    emailAddress.match( / some_regex /);


    Here's an RFC22 regular expression for emails:

    ^((?>[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+\x20*|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*
    "\x20*)*(?<angle><))?((?!\.)(?>\.?[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+)+|"((?=[\x01-\x
    7f])[^"\\]|\\[\x01-\x7f])*")@(((?!-)[a-zA-Z\d\-]+(?<!-)\.)+[a-zA-Z]{2,}|\[(((?(?<
    !\[)\.)(25[0-5]|2[0-4]\d|[01]?\d?\d)){4}|[a-zA-Z\d\-]*[a-zA-Z\d]:((?=[\x01-\x7f])
    [^\\\[\]]|\\[\x01-\x7f])+)\])(?(angle)>)$

    ReplyDelete
  6. Correct validation of email address in compliance with the RFCs is not something that can be achieved with a one-liner regex. Here's a link to an article with the best solution I've found in PHP: http://www.dominicsayers.com/isemail/. Obviously, it has been ported to Java. I think the function is too complex to be ported and used in JavaScript.

    A good practice is to validate your data on the client but double-check the validation on the server. With this in mind, you can simply check whether a string looks like a valid email address on the client and perform the strict check on the server.

    Here's the JS function I use to check if a string looks like a valid mail address:

    function looksLikeMail(str) {
    var lastAtPos = str.lastIndexOf('@');
    var lastDotPos = str.lastIndexOf('.');
    return (lastAtPos < lastDotPos && lastAtPos > 0 && str.indexOf('@@') == -1 && lastDotPos > 2 && (str.length - lastDotPos) > 2);
    }


    Explanation:

    lastAtPos < lastDotPos: Last @ should be before last . since @ cannot be part of server name (as far as I know)

    lastAtPos > 0: There should be something (the email username) before the last @

    str.indexOf('@@') == -1: There should be no @@ in the address. Even if @ appears as the last character in email username, it has to be quoted so " would be between that @ and the last @ in the address.

    lastDotPos > 2: There should be at least 3 characters before the last dot, for example a@b.com

    (str.length - lastDotPos) > 2: There should be enough characters after the last dot to form a two-character domain. I'm not sure if the brackets are necessary.

    ReplyDelete
  7. Don't validate, just send a confirmation email instead.

    ReplyDelete
  8. Answers to the questions Test/expand my email regex or How far should one take e-mail address validation? could easily be adapted for JavaScript

    ReplyDelete
  9. Here is a very good discussion about using regular expressions to validate email addresses; "Comparing E-mail Address Validating Regular Expressions"

    Here is the current top expression, that is JavaScript compatible, for reference purposes:

    /^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i

    ReplyDelete
  10. I've slightly modified Jaymon's answer for people who want really simple validation in the form of:

    anystring@anystring.anystring

    The regex:

    /\S+@\S+\.\S+/


    Example javascript function:

    function validateEmail(email)
    {
    var re = /\S+@\S+\.\S+/;
    return re.test(email);
    }


    (The reason I'm not using the accepted answer is that Chrome was giving syntax errors when I tried to use it).

    ReplyDelete
  11. There is a good example at http://techtamasha.com/?p=47

    ReplyDelete
  12. Apparently, that's it:

    /^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i


    Taken from http://fightingforalostcause.net/misc/2006/compare-email-regex.php on Oct 1 '10.

    But, of course, that's ignoring internationalization.

    ReplyDelete
  13. HTML5 itself has email validation. if your browser support HTML5 then then you can use following code.

    <form><input type="email" placeholder="me@example.com">
    <input type="submit">
    </form>


    jsFiddle link

    ReplyDelete
  14. It's hard to get an email validator 100% correct. The only really way to get it correct would be to send a test email to the account. That said, there are a few basic checks that can help make sure that you're getting something reasonable.

    Some things to improve:

    Instead of new RegExp, just try writing the regexp out like this:

    if (reg.test(/@/))


    Second, check to make sure that a period comes after the @ sign, and make sure that there are characters between the @s and periods.

    ReplyDelete
  15. Use Google's own solution from their Closure library. Very easy to integrate. http://www.sbrian.com/2011/01/javascript-email-address-validation.html

    ReplyDelete
  16. This was stolen from http://codesnippets.joyent.com/posts/show/1917

    email = $('email');
    filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if (filter.test(email.value)) {
    // Yay! valid
    return true;
    }
    else
    {return false;}

    ReplyDelete
  17. Following regular expression:

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

    ReplyDelete
  18. The question is somehow misleading. You should not use reg-exp to validate an input string to check if it's an email: too complicated and would not cover all the cases.

    Now since you can only cover 80% of the cases why not writing something like:

    function isPossiblyValidEmail(txt) {
    return txt.length > 0 && txt.indexOf('@')>0;
    }


    sure you can refine it. For instance 'aaa@' it's valid.
    but overall you get the gist.

    ReplyDelete