Validating email addresses using jQuery and regex

443,899

Solution 1

UPDATES


function isValidEmailAddress(emailAddress) {
    var pattern = /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")@(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;
    return pattern.test(emailAddress);
}

if( !isValidEmailAddress( emailaddress ) ) { /* do stuff here */ }

Solution 2

This is my solution:

function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^[+a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
    // alert( pattern.test(emailAddress) );
    return pattern.test(emailAddress);
};

Found that RegExp over here: http://mdskinner.com/code/email-regex-and-validation-jquery

Solution 3

$(document).ready(function() {
  $('#emailid').focusout(function(){
    $('#emailid').filter(function(){
      var email = $('#emailid').val();
      var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
      if ( !emailReg.test( email ) ) {
        alert('Please enter valid email');
      } else {
        alert('Thank you for your valid email');
      }
    });
  });                 
});

Solution 4

Lolz this is much better

    function isValidEmailAddress(emailAddress) {
        var pattern = new RegExp(/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/);
        return pattern.test(emailAddress);
    };

Solution 5

I would recommend that you use the jQuery plugin for Verimail.js.

Why?

  • IANA TLD validation
  • Syntax validation (according to RFC 822)
  • Spelling suggestion for the most common TLDs and email domains
  • Deny temporary email account domains such as mailinator.com

How?

Include verimail.jquery.js on your site and use the function:

$("input#email-address").verimail({
    messageElement: "p#status-message"
});

If you have a form and want to validate the email on submit, you can use the getVerimailStatus-function:

if($("input#email-address").getVerimailStatus() < 0){
    // Invalid email
}else{
    // Valid email
}
Share:
443,899

Related videos on Youtube

RussP
Author by

RussP

Updated on November 26, 2020

Comments

  • RussP
    RussP over 3 years

    I'm not too sure how to do this. I need to validate email addresses using regex with something like this:

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

    Then I need to run this in a jQuery function like this:

    $j("#fld_emailaddress").live('change',function() { 
    var emailaddress = $j("#fld_emailaddress").val();
    
    // validation here? 
    
    if(emailaddress){}
    
    // end validation
    
    $j.ajax({  
            type: "POST",  
             url: "../ff-admin/ff-register/ff-user-check.php",  
            data: "fld_emailaddress="+ emailaddress,  
            success: function(msg)
            { 
                if(msg == 'OK') { 
                $j("#fld_username").attr('disabled',false); 
                $j("#fld_password").attr('disabled',false); 
                $j("#cmd_register_submit").attr('disabled',false); 
                $j("#fld_emailaddress").removeClass('object_error'); // if necessary
                $j("#fld_emailaddress").addClass("object_ok");
                $j('#email_ac').html('&nbsp;<img src="img/cool.png" align="absmiddle"> <font color="Green"> Your email <strong>'+ emailaddress+'</strong> is OK.</font>  ');
                } else {  
                $j("#fld_username").attr('disabled',true); 
                $j("#fld_password").attr('disabled',true); 
                $j("#cmd_register_submit").attr('disabled',true);  
                $j("#fld_emailaddress").removeClass('object_ok'); // if necessary
                $j("#fld_emailaddress").addClass("object_error");
                $j('#email_ac').html(msg);
                }
            }
         });
    });
    

    Where does the validation go and what is the expression?

  • RussP
    RussP about 14 years
    thanks aSeptik apart from "missing" the e from mailaddress works well yes know that no regex 100% exists, but can get "pretty" close
  • gcb
    gcb about 13 years
    didn't validate that too deep, but it already gave me a false positive for [email protected]
  • Luca Filosofi
    Luca Filosofi about 13 years
    @gcb: hi, if the regex didn't satisfy your needs you can change it, anyway i have tested it and it work fine. jsfiddle.net/ADPaM
  • Luca Filosofi
    Luca Filosofi over 12 years
    your point about the plus sign is valid, but your regex is less better then the one i'm using in my example. ps: i have updated my regex to support plus sign.
  • darwindeeds
    darwindeeds almost 12 years
    Most times you just want to validate that the user entered the email in the right format. To identify typos like "2" instead of "@". So I like this better than the original answer but aSeptik's answer is comprehensive and I up-voted that as well.
  • BerggreenDK
    BerggreenDK over 11 years
    a regex alone on clientside, does not know if there is a mailserver nor if the domain itself exists. it merly checks if the syntax of any email is valid or not. Its only to help the user writing the correct address. its not a validation.
  • Admin
    Admin about 11 years
    Works perfect! Thanks mate
  • Seiyria
    Seiyria almost 11 years
    @aSeptik Hey, I know this is a few years old, but there are some bits of data there that fail and shouldn't, and vice versa.
  • Hexodus
    Hexodus almost 11 years
    I prefer your solution for mobile websites. The other one would bring my smartphone to melt ;) +1
  • Sajith
    Sajith over 10 years
    syntax problem oin javascript
  • Faiz
    Faiz about 10 years
    @aSeptik I have used your code in a recent control I wrote. Hope it is fine with you.. github.com/vpfaiz/EmailArea
  • martindilling
    martindilling about 10 years
    en.wikipedia.org/wiki/Email_address#Valid_email_addresses From this there are only two that don't validate (postbox@com, admin@mailserver1), and it catches all the invalid ones. By far the best regEx I've seen so far ;)
  • Taylor Mitchell
    Taylor Mitchell almost 10 years
    actually this was helpful. The title says JQuery and this is the only answer so far that has a decent jquery example.
  • Daniel Katz
    Daniel Katz almost 10 years
    That regex does not allow addresses like hel\\[email protected] or any escaped forbidden ASCII char in local-part. Source: tools.ietf.org/html/rfc3696, page 5. (Scroll down and the [page #]s are at the top right corner.) But I don't know of any web, that would accept even "\#{; this "@thing.com, which is (I think a correct address) accepted with this regex.
  • D.A.H
    D.A.H almost 10 years
    It will not validate äüõ etc letters!!
  • Sebastian Schmid
    Sebastian Schmid over 8 years
    Verimail keeps validating on keyup, which means, as soon as you start typing, you get an error message. Generally great plugin, but this one is a deal breaker - I would prefer to validate only when triggered manually, i.e. before clicking the submit button or leaving the field.
  • Luca Filosofi
    Luca Filosofi over 8 years
    link to demo restored
  • htngapi
    htngapi about 8 years
    [email protected] it say's vaild - WRONG, change regular expression
  • Elnaz
    Elnaz almost 8 years
    If you had Compilation Error using regex, use @@ instead of @ .
  • TheCrazyProfessor
    TheCrazyProfessor about 7 years
    how can I regex not become 100% ?? emails do always have the same structure so how can it not be possible?
  • NoBullMan
    NoBullMan about 6 years
    this validates [email protected]
  • Sonja
    Sonja about 5 years
    if you want to use this in Razor, in setting up pattern should replace @ with @("@") . Very cool