178

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?

Alireza Sabahi
  • 647
  • 1
  • 12
  • 35
RussP
  • 1,973
  • 3
  • 16
  • 13

10 Answers10

495

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 */ }
Luca Filosofi
  • 30,905
  • 9
  • 70
  • 77
  • 2
    thanks aSeptik apart from "missing" the e from mailaddress works well yes know that no regex 100% exists, but can get "pretty" close – RussP May 19 '10 at 07:46
  • 1
    didn't validate that too deep, but it already gave me a false positive for asdf@adsf.com – gcb Apr 13 '11 at 07:30
  • @gcb: hi, if the regex didn't satisfy your needs you can change it, anyway i have tested it and it work fine. http://jsfiddle.net/ADPaM/ – Luca Filosofi Apr 13 '11 at 10:21
  • 14
    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. – BerggreenDK Jan 09 '13 at 15:29
  • @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. – Seiyria Aug 01 '13 at 00:22
  • @aSeptik I have used your code in a recent control I wrote. Hope it is fine with you.. https://github.com/vpfaiz/EmailArea/ – Faiz Mar 03 '14 at 04:17
  • http://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 ;) – martindilling May 13 '14 at 15:29
  • That regex does not allow addresses like hel\\o@boy.es or any escaped forbidden ASCII char in local-part. Source: http://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. – Daniel Katz Jul 05 '14 at 23:58
  • link to demo restored – Luca Filosofi Sep 18 '15 at 07:27
  • If you had Compilation Error using regex, use @@ instead of @ . – Elnaz Aug 03 '16 at 07:56
  • how can I regex not become 100% ?? emails do always have the same structure so how can it not be possible? – TheCrazyProfessor Mar 30 '17 at 08:20
  • if you want to use this in Razor, in setting up pattern should replace @ with @("@") . Very cool – Sonja Apr 15 '19 at 09:31
30

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

Konstantin Dinev
  • 34,219
  • 14
  • 75
  • 100
Bjørn Børresen
  • 1,002
  • 11
  • 20
  • 3
    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. – Luca Filosofi Oct 21 '11 at 21:18
  • 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. – darwindeeds Jul 18 '12 at 18:22
  • test@gmail..com it say's vaild - WRONG, change regular expression – htngapi Mar 30 '16 at 02:58
14
$(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');
      }
    });
  });                 
});
Karim Tarek
  • 797
  • 4
  • 18
webizon
  • 149
  • 1
  • 3
7

Lolz this is much better

    function isValidEmailAddress(emailAddress) {
        var pattern = new RegExp(/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/);
        return pattern.test(emailAddress);
    };
Code Spy
  • 9,626
  • 4
  • 66
  • 46
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
}
Robin Orheden
  • 2,714
  • 23
  • 24
  • 1
    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. – Sebastian Schmid Sep 15 '15 at 17:27
1

Javascript:

var pattern = new RegExp("^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
var result = pattern .test(str);


The regex is not allowed for:

abc@gmail..com
abc@gmail.com..


Allowed for:

abc.efg@gmail.com
abc@gmail.com.my

Source: http://www.mkyong.com/regular-expressions/10-java-regular-expression-examples-you-should-know/

sky91
  • 3,060
  • 2
  • 19
  • 26
0

Try this

function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/);
    return pattern.test(emailAddress);
};
Purvik Dhorajiya
  • 4,662
  • 3
  • 34
  • 43
0

you can use this function

 var validateEmail = function (email) {

        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;


        if (pattern.test(email)) {
            return true;
        }
        else {
            return false;
        }
    };
Nikki
  • 409
  • 1
  • 5
  • 15
0

Native method:

$("#myform").validate({
 // options...
});

$.validator.methods.email = function( value, element ) {
  return this.optional( element ) || /[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}/.test( value );
}

Source: https://jqueryvalidation.org/jQuery.validator.methods/

BroFox
  • 61
  • 4
0

We can also use regular expression (/^([\w.-]+)@([\w-]+)((.(\w){2,3})+)$/i) to validate email address format is correct or not.

var emailRegex = new RegExp(/^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$/i);
 var valid = emailRegex.test(emailAddress);
  if (!valid) {
    alert("Invalid e-mail address");
    return false;
  } else
    return true;
Blender
  • 289,723
  • 53
  • 439
  • 496
Avinash
  • 199
  • 1
  • 2