How to validate email address in JavaScript?

    |
  • Added:
  • |
  • In: Wordpress

How can an email address be validated in JavaScript?

This Question Has 30 Answeres | Orginal Question | pix0r

What you think about my solution here: How to use Angular input fields email validation inside controller?

Basically you can create a hidden input field of type email and using javascript set the value to that input and check if it's valid.

The best practice is to either use HTML5 built-in email tag.

<input type="email" name="email"> 

or the common email syntax as recognizing @ and . from the string is given below.

^[a-zA-Z0-9_\-.]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-.]+$ 

Note that this would still produce invalid email that will still match the regex, its almost impossible to catch them all but this will improve the situation a little.

Wikipedia standard mail syntax :

https://en.wikipedia.org/wiki/Email_address#Examples https://fr.wikipedia.org/wiki/Adresse_%C3%A9lectronique#Syntaxe_exacte

function validMail(mail) { return /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()\.,;\s@\"]+\.{0,1})+([^<>()\.,;:\s@\"]{2,}|[\d\.]+))$/.test(mail); } // VALID MAILS validMail('Abc@example.com') // Return true validMail('Abc@example.com.') // Return true validMail('Abc@10.42.0.1') // Return true validMail('user@localserver') // Return true validMail('Abc.123@example.com') // Return true validMail('user+mailbox/department=shipping@example.com') // Return true validMail('"very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@strange.example.com') // Return true validMail('!#$%&\'*+-/=?^_`.{|}~@example.com') // Return true validMail('"()<>[]:,;@\\\"!#$%&\'-/=?^_`{}| ~.a"@example.org') // Return true validMail('"Abc@def"@example.com') // Return true validMail('"Fred Bloggs"@example.com') // Return true validMail('"Joe.\\Blow"@example.com') // Return true validMail('Loïc.Accentué@voilà.fr') // Return true validMail('" "@example.org') // Return true validMail('user@[IPv6:2001:DB8::1]') // Return true // INVALID MAILS validMail('Abc.example.com') // Return false validMail('A@b@c@example.com') // Return false validMail('a"b(c)d,e:f;g<h>i[j\k]l@example.com') // Return false validMail('just"not"right@example.com') // Return false validMail('this is"not\allowed@example.com') // Return false validMail('this\ still\"not\\allowed@example.com') // Return false validMail('john..doe@example.com') // Return false validMail('john.doe@example..com') // Return false 

Show this test : https://regex101.com/r/LHJ9gU/1

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}$/; 

Whoever is using @pvl solution and wants it to pass ESLint Prefer-template then here's a version where I used template literals instead of string concatenation.

validateEmail(email) { let sQtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]'; let sDtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]'; let sAtom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+'; let sQuotedPair = '\\x5c[\\x00-\\x7f]'; let sDomainLiteral = `\\x5b(${sDtext}|${sQuotedPair})*\\x5d`; let sQuotedString = `\\x22(${sQtext}|${sQuotedPair})*\\x22`; let sDomainRef = sAtom; let sSubDomain = `(${sDomainRef}|${sDomainLiteral})`; let sWord = `(${sAtom}|${sQuotedString})`; let sDomain = `${sSubDomain}(\\x2e${sSubDomain})*`; let sLocalPart = `${sWord}(\\x2e${sWord})*`; let sAddrSpec = `${sLocalPart}\\x40${sDomain}`; // complete RFC822 email address spec let sValidEmail = `^${sAddrSpec}$`; // as whole string let reValidEmail = new RegExp(sValidEmail); return reValidEmail.test(email); } 

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

anystring@anystring.anystring

The regular expression:

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

Example JavaScript function:

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

This regexp prevents duplicate domain names like abc@abc.com.com.com.com, it will allow only domain two time like abc@abc.co.in. It also does not allow statring from number like 123abc@abc.com

regexp: /^([a-zA-Z])+([a-zA-Z0-9_.+-])+\@(([a-zA-Z])+\.+?(com|co|in|org|net|edu|info|gov|vekomy))\.?(com|co|in|org|net|edu|info|gov)?$/, 

All The Best !!!!!

If you're using Closure you can use the built-in goog.format.EmailAddress type:

http://docs.closure-library.googlecode.com/git/class_goog_format_EmailAddress.html

For example:

goog.format.EmailAddress.isValidAddrSpec("blah@blah.com") 

Note that by reading the source (linked above) you can see the comments state that IDN are not supported and that it only aims to cover most addresses:

// This is a fairly naive implementation, but it covers 99% of use cases. // For more details, see http://en.wikipedia.org/wiki/Email_address#Syntax // TODO(mariakhomenko): we should also be handling i18n domain names as per // http://en.wikipedia.org/wiki/Internationalized_domain_name 

How about creating a function which will test any string against emails' pattern using regular expression in JavaScript, as we know email addresses can be quite different in different regions, like in UK and Australia it usually ends up with .co.uk or .com.au, so I tried to cover those as well, also check if the string passed to the function, something like this:

var isEmail = function(str) { return typeof str==='string' && /^[\w+\d+._]+\@[\w+\d+_+]+\.[\w+\d+._]{2,8}$/.test(str); } 

and check if it's email like below:

isEmail('alex@example.com'); //true isEmail('alireza@test.co.uk'); //true isEmail('peter.example@yahoo.com.au'); //true isEmail('alex@example.com'); //true isEmail('peter_123@news.com'); //true isEmail('hello7___@ca.com.pt'); //true isEmail('example@example.co'); //true isEmail('hallo@example.coassjj#sswzazaaaa'); //false isEmail('hallo2ww22@example....caaaao'); //false 

HTML5 itself has email validation. If your browser supports HTML5 then you can use the following code.

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

jsFiddle link

From the HTML5 spec:

A valid e-mail address is a string that matches the email production of the following ABNF, the character set for which is Unicode.

email = 1*( atext / "." ) "@" label *( "." label ) label = let-dig [ [ ldh-str ] let-dig ] ; limited to a length of 63 characters by RFC 1034 section 3.5 atext = < as defined in RFC 5322 section 3.2.3 > let-dig = < as defined in RFC 1034 section 3.5 > ldh-str = < as defined in RFC 1034 section 3.5 > 

This requirement is a willful violation of RFC 5322, which defines a syntax for e-mail addresses that is simultaneously too strict (before the "@" character), too vague (after the "@" character), and too lax (allowing comments, whitespace characters, and quoted strings in manners unfamiliar to most users) to be of practical use here.

The following JavaScript- and Perl-compatible regular expression is an implementation of the above definition.

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

best regex ever which confirm RFC5322

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

In contrast to squirtle, here is a complex solution, but it does a mighty fine job of validating emails properly:

function isEmail(email) { return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\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]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([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.test(email); } 

Use like so:

if (isEmail('youremail@yourdomain.com')){ console.log('This is email is valid'); } 

In nodeJS you can also use validator node module and simply use like that

Install the library with npm install validator

var validator = require('validator'); validator.isEmail('foo@bar.com'); //=> true 

I have found this to be the best solution:

/^[^\s@]+@[^\s@]+\.[^\s@]+$/ 

It allows the following formats:

 1. prettyandsimple@example.com 2. very.common@example.com 3. disposable.style.email.with+symbol@example.com 4. other.email-with-dash@example.com 9. #!$%&'*+-/=?^_`{}|~@example.org 6. "()[]:,;@\\\"!#$%&'*+-/=?^_`{}| ~.a"@example.org 7. " "@example.org (space between the quotes) 8. üñîçøðé@example.com (Unicode characters in local part) 9. üñîçøðé@üñîçøðé.com (Unicode characters in domain part) 10. Pelé@example.com (Latin) 11. ??????@??????????.?????? (Greek) 12. ??@??.?? (Chinese) 13. ??@??.?? (Japanese) 14. ?????????@????-?-???????????.?? (Cyrillic) 

It's clearly versatile and allows the all-important international characters, while still enforcing the basic anything@anything.anything format. It will block spaces which are technically allowed by RFC, but they are so rare that I'm happy to do this.

I was looking for a Regex in JS that passes all Email Address test cases:

  • email@domain.com Valid email

  • firstname.lastname@domain.com Email contains dot in the address field

  • email@subdomain.domain.com Email contains dot with subdomain

  • firstname+lastname@domain.com Plus sign is considered valid character

  • email@123.123.123.123 Domain is valid IP address

  • email@[123.123.123.123] Square bracket around IP address is considered valid

  • “email”@domain.com Quotes around email is considered valid

  • 1234567890@domain.com Digits in address are valid

  • email@domain-one.com Dash in domain name is valid

  • _______@domain.com Underscore in the address field is valid

  • email@domain.name .name is valid Top Level Domain name

  • email@domain.co.jp Dot in Top Level Domain name also considered valid (use co.jp as example here)

  • firstname-lastname@domain.com Dash in address field is valid

Here we go :

http://regexr.com/3f07j

OR regex:

Regex = /(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@[*[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+]*/ 

You can also use this reusable is-email component which runs this regex and returns a boolean without duplicating it in multiple places.

How it works:

function isEmail(email) { const 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); }; 

Using regular expressions is probably the best way. You can see a bunch of tests here (taken from chromium)

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); } 

Here's the example of regular expresion that accepts unicode:

var re = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i; 

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.

Here's an example of the above in action:

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); } function validate() { $("#result").text(""); var email = $("#email").val(); if (validateEmail(email)) { $("#result").text(email + " is valid :)"); $("#result").css("color", "green"); } else { $("#result").text(email + " is not valid :("); $("#result").css("color", "red"); } return false; } $("#validate").bind("click", validate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <p>Enter an email address:</p> <input id='email'> <button type='submit' id='validate'>Validate!</button> </form> <h2 id='result'></h2>

Simple regex for email-Id

 String EMAIL_PATTERN ="^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$"; 

If you want to use Jquery and want to have modern approach then use JQuery input mask with validation.

http://bseth99.github.io/projects/jquery-ui/5-jquery-masks.html

Demo on how simple jquery input mask is here: http://codepen.io/anon/pen/gpRyBp

Example of simple input mask for date forexample NOT full validation

 <input id="date" type="text" placeholder="YYYY-MM-DD"/> 

and the script:

 $("#date").mask("9999-99-99",{placeholder:"YYYY-MM-DD"}); 

I've mixed @mevius and @Boldewyn Code to Create this ultimate code for email verification using JavaScript.

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,}))$/; var input = document.createElement('input'); input.type = 'email'; input.value = email; return typeof input.checkValidity == 'function' ? input.checkValidity() : re.test(email); }

I have shared this code on my blog here.

Following Regex validations:

  • No spacial characters before @
  • (-) and (.) should not be together after @
  • No special characters after @ 2 characters must before @
  • Email length should be less 128 characters

    function validateEmail(email) { var chrbeforAt = email.substr(0, email.indexOf('@')); if (!($.trim(email).length > 127)) { if (chrbeforAt.length >= 2) { var re = /^(([^<>()[\]{}'^?\\.,!|//#%*-+=&;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/; return re.test(email); } else { return false; } } else { return false; } } 

Use the regular expression:

 /^[a-z][a-zA-Z0-9_.]*(\.[a-zA-Z][a-zA-Z0-9_.]*)?@[a-z][a-zA-Z-0-9]*\.[a-z]+(\.[a-z]+)?$/ 

Example:

function validateEmail(email) { var re = /^[a-z][a-zA-Z0-9_.]*(\.[a-zA-Z][a-zA-Z0-9_.]*)?@[a-z][a-zA-Z-0-9]*\.[a-z]+(\.[a-z]+)?$/; return re.test(email); } 

It should allow only @ , . , _

If you are using AngularJS, just add type="email" to the input element:

https://docs.angularjs.org/api/ng/input/input%5Bemail%5D

In case there is no input element, it can be created dynamically:

var isEmail = $compile('<input ng-model="m" type="email">')($rootScope.$new()). controller('ngModel').$validators["email"]; if (isEmail('email@gmail.com')) { console.log('valid'); } 

If you are using ng-pattern and material this does the job.

vm.validateEmail = '([a-zA-Z0-9_.]{1,})((@[a-zA-Z]{2,})[\\\.]([a-zA-Z]{2}|[a-zA-Z]{3}))'; 

Now ReactNative Version 0.46 Use Below code for email Validation.

 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,}))$/; if (re.test(email)) { } else { alert('email: ' + "Please enter valid emailID.") } } 

There are some complex RegEx written here, that also works.

I tested this one and it works too:

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

Please test this here : http://www.regextester.com/?fam=97334

Hope this helps.

I'm really looking forward to solve this problem. So I modified email validation regular expression above

  • Original
    /^(([^<>()\[\]\\.,;:\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,}))$/

  • Modified
    /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()\.,;\s@\"]+\.{0,1})+[^<>()\.,;:\s@\"]{2,})$/

to pass the examples in Wikipedia Email Address.

And you can see the result in here.

enter image description here

ES6 sample

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

I'd like to add a short note about non-ASCII characters. Rnevius's (and co.) solution is brilliant, but it allows to add Cyrillic, Japanese, Emoticons and other unicode symbols which may be restricted by some servers.

The code below will print true though it contains UTF-8 character ?.

console.log (/^(([^<>()\[\]\\.,;:\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,}))$/.test ('?@example.org'))

In my case all non-ASCII symbols are prohibited so I have modified the original expression to exclude all characters above U+007F:

/^(([^\u0080-\uffff<>()\[\]\\.,;:\s@"]+(\.[^\u0080-\uffff<>()\[\]\\.,;:\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,}))$/

Maybe this will help someone to prevent undesired behaviour.

A solution that does not check the existence of the TLD is incomplete.

Almost all answers to this questions suggest using Regex to validate emails addresses. I think Regex is only good for a rudimentary validation. It seems that the checking validation of email addresses is actually two separate problems:

1- Validation of email format: Making sure if the email complies with the format and pattern of emails in RFC 5322 and if the TLD actually exists. A list of all valid TLDs can be found here.

For example, although the address example@example.ccc will pass the regex, it is not a valid email, because ccc is not a top-level domain by IANA.

2- Making sure the email actually exists: For doing this, you just need to send the users an email.


Search
I am...

Sajjad Hossain

I have five years of experience in web development sector. I love to do amazing projects and share my knowledge with all.

Connect Social With PHPAns
Top