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 = "azamsharp@gmail.com";      

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

}
yunandtidus
  • 3,847
  • 3
  • 29
  • 42
azamsharp
  • 19,710
  • 36
  • 144
  • 222
  • 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. – AnthonyWJones Jun 02 '09 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. –  Nov 28 '13 at 04:01
  • Why can't you just use type = "email" within the form? @azamsharp – PT_C Oct 08 '14 at 14:23

16 Answers16

108

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

James
  • 109,676
  • 31
  • 162
  • 175
  • 41
    This regular expression doesn't support addresses like john.smith@gmail.com – Nadia Alramli Jun 02 '09 at 16:46
  • This is not for any production application. This is for a small demo I am creating. Thanks for pointing that out though! – azamsharp Jun 02 '09 at 16:49
  • 6
    it doesn't support emails like emailadd@gmail.com.sa – Amr Badawy May 16 '10 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). – Ciaran Gallagher Mar 24 '13 at 15:38
  • I mean I'm sure it's suitable across a local network or a reliable network connection, but otherwise surely it might be problematic. – Ciaran Gallagher Mar 24 '13 at 15:52
  • 1
    This won't support email addresses like: bob+tag@gmail.com, bob@foo123.com, and bob.sagat@gmail.com (as Nadia Alramli already pointed out) – Aneil Mallavarapu Jan 26 '14 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 Jan 26 '14 at 20:45
  • 1
    @CiaranGallagher, you're right about performance. However, from a security standpoint, client side JS wouldn't protect you from XSS, SQL injection, or other vulnerabilities. IMHO, it's best to do some basic validation on the front end so that your users don't lose the data they entered (EX: check for empty fields, validate phone numbers or SSN). However, you should always secure your application with open source high caliber sanitization code on the server. – Rustavore Jul 10 '14 at 19:08
  • This should not be the accepted answer. This is wrong! See the comments above for details! – Dziad Borowy Nov 04 '16 at 09:01
  • Client side validation is important, no matter if it is email or something else. Above all, If you have unique data like contacts, emails, NIDs and so on so forth, then it is very good to validate their uniqueness on one of the following cases: onblur, onkeyupp, onkeypress, ... It depends on you choice. In this case you can reduce time waste. – maruf najm Feb 01 '17 at 06:00
  • This answer does not support numbers in emails. Terrible. I know that this was just a partial answer but it should state that in the answer. – Mauvis Ledford Apr 10 '18 at 05:25
  • Domains of highest level can have more than 3 letters: data.iana.org/TLD/tlds-alpha-by-domain.txt – Daniel Apr 22 '18 at 20:21
  • 1
    This is a working simple script that the OP asked for. Email validation shouldn't be done because it can't/is too difficult and troublesome. If you're that worried about validating it then send and email with a token. Create your validation return. Outside of that we can only try to see if it has an @ symbol and isn't empty and is under a max string count. Why? You can create ridiculous emails and you'd spend more time and resources creating the regex to be perfect. EMAIL regex is up to the designer. What works for you. The regex isn't going to be perfect. Maybe perfectly imperfect. – JSG Apr 24 '18 at 19:15
  • It does not also support an email like: emailid@my-domain.com – Hossein Abedi Apr 30 '18 at 14:16
  • You can also format a string as "raw" in order to make sure escaped keys aren't processed (`\n`, `\b`, etc.). A string can be formatted as "raw" using the following syntax: `var str = String.raw\`The quick brown fox jumped over the lazy dog.\`` _(Courtesy of [MDN web docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/raw).)_ – Lathryx Nov 09 '20 at 16:54
  • This /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/ also work in php – Talemul Islam Mar 03 '22 at 16:32
  • ALERT!! this regex don't support patterns like **wasit185290@st.jmi.ac.in**, which is my valid university email address – Wasit Shafi Aug 15 '23 at 11:52
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}$/

Thiem Nguyen
  • 6,345
  • 7
  • 30
  • 50
rat
  • 415
  • 4
  • 2
16

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;
}
rcastera
  • 309
  • 2
  • 4
  • 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 Mar 30 '12 at 14:46
  • I think that your regex doesn't validate for, let's say, nicolas.@gmail.com... Is this RFC822 compliant? I am not sure. Anybody to validate? – nembleton May 30 '12 at 13:55
  • It gives aaa-------@gmail.com as true – Imran Ahmad Apr 23 '18 at 18:45
12

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

Shafiqul Islam
  • 5,570
  • 2
  • 34
  • 43
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)

Community
  • 1
  • 1
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
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.

Mohamad Shiralizadeh
  • 8,329
  • 6
  • 58
  • 93
M.R.Safari
  • 1,857
  • 3
  • 30
  • 47
  • 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_ Jan 28 '14 at 10:51
8
function isEmailAddress(str) {
   var pattern =/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
   return pattern.test(str);  // returns a boolean 
}
Nanhe Kumar
  • 15,498
  • 5
  • 79
  • 71
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:

  • test@gnail.com -> Did you mean test@gmail.com?
  • test@hottmail.con -> Did you mean test@hotmail.com?

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 test@gmail.com?". 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.

Robin Orheden
  • 2,714
  • 23
  • 24
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)$/;
Sabeeh Chaudhry
  • 6,244
  • 1
  • 16
  • 8
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("exampleemail@testing.info")

returns true if it works

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

Alex V
  • 18,176
  • 5
  • 36
  • 35
  • 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 Apr 22 '18 at 20:23
  • Also, email@domains-with-hyphen.com will not pass this condition – Madhu Dollu Jul 09 '22 at 08:35
3

I have been using this one....

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

It allows that + before @ (xyz+abc@xyz.com)

teacher
  • 1,005
  • 3
  • 15
  • 27
3

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/

Yasser Shaikh
  • 46,934
  • 46
  • 204
  • 281
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');
Santron Manibharathi
  • 628
  • 5
  • 12
  • 26
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 />";
}
Gaurav Gupta
  • 478
  • 6
  • 10
  • `test@test.info` returns false – Dziad Borowy Nov 04 '16 at 09:11
  • I've tested this pattern and it works for all valid combinations, like `name.surname@domain.com`, `name.surname+label@domain.com`and even for `name@domain.info` (first level domain with 4 chars) – shimatai Apr 16 '18 at 02:55
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. someone@gmail.com will also get email sent to someone+else@gmail.com).

micky.o'finnagan@wherever.com 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

pete otaqui
  • 1,432
  • 14
  • 11
-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 = "test.email@example.com";

if(user_email.isEmail()) {
    //Email is valid !
} else {
    //Email is invalid !
}
CORSAIR
  • 512
  • 6
  • 14