152

This code is always alerting out "null", which means that the string does not match the expression.

var pattern = "^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$"; 

function isEmailAddress(str) {

    str = "[email protected]";      

    alert(str.match(pattern)); 
    return str.match(pattern);    

}
3
  • 7
    Email validation is hard. Pragmatically you can only assume it contains one @ and that there is at least one . following the @ somewhere but thats about it really if you want to avoid alienating at least some of your users. Unless you are validating for a specific domain where the email naming policy is more structured. Commented Jun 2, 2009 at 16:50
  • 1
    Strictly speaking you can't even assume there is a . somewhere. See for example the ua ccTLD, which has MX records at the top level.
    – user1311045
    Commented Nov 28, 2013 at 4:01
  • Why can't you just use type = "email" within the form? @azamsharp
    – PT_C
    Commented Oct 8, 2014 at 14:23

16 Answers 16

109

If you define your regular expression as a string then all backslashes need to be escaped, so instead of '\w' you should have '\\w'.

Alternatively, define it as a regular expression:

var pattern = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/; 

BTW, please don't validate email addresses on the client-side. Your regular expression is way too simple to pass for a solid implementation anyway.

See the real thing here: http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html

17
  • 42
    This regular expression doesn't support addresses like [email protected] Commented Jun 2, 2009 at 16:46
  • 6
    it doesn't support emails like [email protected]
    – Amr Badawy
    Commented May 16, 2010 at 12:28
  • 6
    Why shouldn't the email addresses be validated client side? Surely it's a much faster form of validation client side, since we don't need to make multiple HTTP requests across a network to validate the data? (which is particularly important for mobile applications which may be contacting a server via slow Wifi or mobile networks). Commented Mar 24, 2013 at 15:38
  • 1
    This won't support email addresses like: [email protected], [email protected], and [email protected] (as Nadia Alramli already pointed out) Commented Jan 26, 2014 at 19:49
  • 2
    This expression leaves a whole lot to be desired: 1) disallows many valid username characters such as dash and plus; 2) disallows domains with more than 2 parts, found in many ccTLDs, such as geek.co.il; 3) disallows many of the new TLDs that use 4 or more characters, such as mobi and info; 4) doesn't support IDN at all.
    – Guss
    Commented Jan 26, 2014 at 20:45
39

this is the one i am using on my page.

http://www.zparacha.com/validate-email-address-using-javascript-regular-expression/

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

3
17

I've been using this function for a while. it returns a boolean value.

// Validates email address of course.
function validEmail(e) {
    var filter = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
    return String(e).search (filter) != -1;
}
3
  • 1
    I know this is old, but this can be simplified to: return String(e).match(/^\s*[\w\-\+_]+(?:\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(?:\.[\w\-\+_]+)*\s*$/); It will return null if no match and a single item array of the email address itself if it does match.
    – Andir
    Commented Mar 30, 2012 at 14:46
  • I think that your regex doesn't validate for, let's say, [email protected]... Is this RFC822 compliant? I am not sure. Anybody to validate?
    – nembleton
    Commented May 30, 2012 at 13:55
  • It gives [email protected] as true Commented Apr 23, 2018 at 18:45
13

Sometimes most of the registration and login page need to validate email. In this example you will learn simple email validation. First take a text input in html and a button input like this

<input type='text' id='txtEmail'/>
<input type='submit' name='submit' onclick='checkEmail();'/>

<script>
    function checkEmail() {
        var email = document.getElementById('txtEmail');
        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>

you can also check using this regular expression

<input type='text' id='txtEmail'/>
<input type='submit' name='submit' onclick='checkEmail();'/>

<script>
    function checkEmail() {

        var email = document.getElementById('txtEmail');
        var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

        if (!filter.test(email.value)) {
            alert('Please provide a valid email address');
            email.focus;
            return false;
        }
    }
</script>

Check this demo output which you can check here

function checkEmail() {
        var email = document.getElementById('txtEmail');
        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;
        }
    }
<input type='text' id='txtEmail'/>
<input type='submit' name='submit' onclick='checkEmail();'/>

if email invalid then give alert message , if valid email then no alert message . for more info about regular expression

https://www.w3schools.com/jsref/jsref_obj_regexp.asp

hope it will help you

2
  • What is the point of the {2,4} if you have a + after it? Commented May 18, 2015 at 21:48
  • then it will show invalid email , can you give me sample email address ? Commented Aug 29, 2016 at 18:22
11

You may be interested in this question (or this one), which highlights the fact that identifying valid email addresses via regexps is a very hard problem to solve (if at all solvable)

10

with more simple

Here it is :

var regexEmail = /\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
var email = document.getElementById("txtEmail");

if (regexEmail.test(email.value)) {
    alert("It's Okay")
} else {
    alert("Not Okay")

}

good luck.

1
  • at the point of writing this, this worked well.... let's hope it stays that way as i've been through quite a few of these ;)
    – AO_
    Commented Jan 28, 2014 at 10:51
8
function isEmailAddress(str) {
   var pattern =/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
   return pattern.test(str);  // returns a boolean 
}
1
5

Email validation is easy to get wrong. I would therefore recommend that you use Verimail.js.

Why?

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

Another great thing with Verimail.js is that it has spelling suggestion for the most common email domains and registered TLDs. This can lower your bounce rate drastically for users that misspell common domain names such as gmail.com, hotmail.com, aol.com, aso..

Example:

How to use it?

The easiest way is to download and include verimail.jquery.js on your page. After that, hookup Verimail by running the following function on the input-box that needs the validation:

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

The message element is an optional element that displays a message such as "Invalid email.." or "Did you mean [email protected]?". If you have a form and only want to proceed if the email is verified, you can use the function getVerimailStatus as shown below:

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

The getVerimailStatus-function returns an integer code according to the object Comfirm.AlphaMail.Verimail.Status. As shown above, if the status is a negative integer value, then the validation should be treated as a failure. But if the value is greater or equal to 0, then the validation should be treated as a success.

4

You can also try this expression, I have tested it against many email addresses.

var pattern = /^[A-Za-z0-9._%+-]+@([A-Za-z0-9-]+\.)+([A-Za-z0-9]{2,4}|museum)$/;
4

Little late to the party, but here goes nothing...

function isEmailValid(emailAdress) {
    var EMAIL_REGEXP = new RegExp('^[a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,15})$', 'i');
    return EMAIL_REGEXP.test(emailAdress)
}

http://jsfiddle.net/yrshaikh/xvd6H/

3
  • a@c om is not a valid email and it passes this pattern Commented Nov 4, 2016 at 9:03
  • this regex was not tested thoroughly.
    – Brandon
    Commented Dec 12, 2017 at 14:17
  • @Brandon ok and? Commented Dec 14, 2017 at 8:24
4

It would be best to use:

var pattern = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,20}$/;

This allows domains such as: whatever.info (4 letters at the end)

Also to test, using

pattern.test("[email protected]")

returns true if it works

http://www.w3schools.com/js/js_obj_regexp.asp

2
  • Domains of highest level can have more than 4 letters: data.iana.org/TLD/tlds-alpha-by-domain.txt, domain '.academy' or '.afamilycompany' do not pass your condition.
    – Daniel
    Commented Apr 22, 2018 at 20:23
  • Also, [email protected] will not pass this condition Commented Jul 9, 2022 at 8:35
3

I have been using this one....

/^[\w._-]+[+]?[\w._-]+@[\w.-]+\.[a-zA-Z]{2,6}$/

It allows that + before @ ([email protected])

2
  • This is the only pattern here, that actually works!! Commented Nov 4, 2016 at 9:12
  • Nope, there are domain tld's longer than 6 characters, like .software for instance.
    – Mike Doe
    Commented Mar 1, 2018 at 11:20
2
var emailRegex = /^[A-Z0-9_'%=+!`#~$*?^{}&|-]+([\.][A-Z0-9_'%=+!`#~$*?^{}&|-]+)*@[A-Z0-9-]+(\.[A-Z0-9-]+)+$/i;
if(emailRegex.test('yoursamplemail'))
alert('valid');
else
alert('invalid');
1
  • Worked for me, tnx
    – Starwave
    Commented Mar 16, 2018 at 10:54
1

Simple but powerful email validation for check email syntax :

var EmailId = document.getElementById('Email').value;
var emailfilter = /^[\w._-]+[+]?[\w._-]+@[\w.-]+\.[a-zA-Z]{2,6}$/;
if((EmailId != "") && (!(emailfilter.test(EmailId ) ) )) {
    msg+= "Enter the valid email address!<br />";
}
2
0

You should bear in mind that a-z, A-Z, 0-9, ., _ and - are not the only valid characters in the start of an email address.

Gmail, for example, lets you put a "+" sign in the address to "fake" a different email (e.g. [email protected] will also get email sent to [email protected]).

micky.o'[email protected] would not appreciate your code stopping them entering their address ... apostrophes are perfectly valid in email addresses.

The Closure "check" of a valid email address mentioned above is, as it states itself, quite naïve:

http://code.google.com/p/closure-library/source/browse/trunk/closure/goog/format/emailaddress.js#198

I recommend being very open in your client side code, and then much more heavyweight like sending an email with a link to really check that it's "valid" (as in - syntactically valid for their provider, and also not misspelled).

Something like this:

var pattern = /[^@]+@[-a-z\.]\.[a-z\.]{2,6}/

Bearing in mind that theoretically you can have two @ signs in an email address, and I haven't even included characters beyond latin1 in the domain names!

http://www.eurid.eu/en/eu-domain-names/idns-eu

http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx

-1

You can add a function to String Object

//Add this wherever you like in your javascript code
String.prototype.isEmail = function() {
    return !!this.match(/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/);
}

var user_email = "[email protected]";

if(user_email.isEmail()) {
    //Email is valid !
} else {
    //Email is invalid !
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.