How to validate an email address in JavaScript
How can an email address be validated in JavaScript?
Answers
How to write Particular Regular Expression in android or java.
1) USER_NAME = "^[A-Za-z0-9_-]{min number of character,max number of character}$";
2) TELEPHONE = "(^\\+)?[0-9()-]*";
3) TELEPHONE_OPTIONAL = "^($|(^\\+)?[0-9()-]*)$";
4) EMAIL = "[a-zA-Z0-9_\\.\\+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-\\.]+";
5) EMAIL_OPTIONAL = "^($|[a-zA-Z0-9_\\.\\+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-\\.]+)$";
6) WEB_URL = "^($|(http:\\/\\/|https:\\/\\/)?(www.)?([a-zA-Z0-9]+).[a-zA-Z0-9]*.[a-z]{3}.?([a-z]+)?)$";
7) WEB_URL_YOUTUBE_BE = "https?\\:\\/\\/(www\\.)?youtu(\\.)?be(\\.com)?\\/.*(\\?v=|\\/v\\/)?[a-zA-Z0-9_\\-]+";
8) POSTAL_ADDRESS = "[a-zA-Z\\d\\s\\-\\,\\#\\.\\+]+";
9) FIELD_NOT_EMPTY = "[^\\s]*";
10) PINCODE = "^([0-9]{6})?$";
11) IFSC_CODE = "^[^\\s]{4}\\d{7}$";
12) SWIFT_CODE = "^([0-9]{10})?$";
13) PINCODE = "^([0-9]{6})?$";
Sectrean's solution works great, but it was failing my linter. So I added some escapes:
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); }
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 was looking for a Regex in JS that passes all Email Address test cases:
email@example.com Valid email
firstname.lastname@example.com Email contains dot in the address field
email@subdomain.example.com Email contains dot with subdomain
firstname+lastname@example.com Plus sign is considered valid character
email@192.0.2.123 Domain is valid IP address
email@[192.0.2.123] Square bracket around IP address is considered valid
“email”@example.com Quotes around email is considered valid
1234567890@example.com Digits in address are valid
email@domain-one.example Dash in domain name is valid
_______@example.com Underscore in the address field is valid
email@example.name .name is valid Top Level Domain name
email@example.co.jp Dot in Top Level Domain name also considered valid (using co.jp as example here)
firstname-lastname@example.com Dash in address field is valid
Here we go :
OR regex:
Regex = /(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@[*[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+]*/
Here is a function I use for front end email validation. (The Regular Expression came from parsley.js)
<!DOCTYPE html> <html> <head> <title>Our Company</title> <style> .form-style { color: #ccc; } </style> </head> <body> <h1>Email Validation Form Example</h1> <input type="text" name="email" id="emailInput" class="form-style"> <script> function validateEmail(emailAddress) { var regularExpression = /^((([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]))){2,6}$/i; return regularExpression.test(emailAddress); } function showEmailValidationState(event) { if (validateEmail(event.target.value)) { document.getElementById("emailInput").style.color = 'black'; } } document.getElementById("emailInput").addEventListener("keyup", showEmailValidationState); </script> </body> </html>
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.
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])?/; //var re = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[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 @ , . , _
You can also try
var string = "hmharsh3@gmail.com" var exp = /(\w(=?@)\w+\.{1}[a-zA-Z]{2,})/i alert(exp.test(string))
This is a JavaScript translation of the validation suggested by the official Rails guide used by thousands of websites:
/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
Relatively simple but tests against most common errors.
Tested on a dataset of thousands of emails and it had zero false negatives/positives.
Example usage:
const emailRegex = /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i; emailRegex.test('email@example.com'); // true // Multi-word domains emailRegex.test('email@example.co.uk'); // true emailRegex.test('email@mail.gmail.com'); // true // Valid special characters emailRegex.test('unusual+but+valid+email1900=/!#$%&\'*+-/=?^_`.{|}~@example.com') // true // Trailing dots emailRegex.test('email@example.co.uk.'); // false // No domain emailRegex.test('email@example'); // false // Leading space emailRegex.test(' email@example.com'); // false // Trailing space emailRegex.test('email@example.com '); // false // Incorrect domains emailRegex.test('email@example,com '); // false // Other invalid emails emailRegex.test('invalid.email.com') // false emailRegex.test('invalid@email@domain.com') // false emailRegex.test('email@example..com') // false
<pre> **The personal_info part contains the following ASCII characters. 1.Uppercase (A-Z) and lowercase (a-z) English letters. 2.Digits (0-9). 3.Characters ! # $ % & ' * + - / = ? ^ _ ` { | } ~ 4.Character . ( period, dot or fullstop) provided that it is not the first or last character and it will not come one after the other.** </pre> *Example of valid email id* <pre> yoursite@ourearth.com my.ownsite@ourearth.org mysite@you.me.net xxxx@gmail.com xxxxxx@yahoo.com </pre> <pre> xxxx.ourearth.com [@ is not present] xxxx@.com.my [ tld (Top Level domain) can not start with dot "." ] @you.me.net [ No character before @ ] xxxx123@gmail.b [ ".b" is not a valid tld ] xxxx@.org.org [ tld can not start with dot "." ] .xxxx@mysite.org [ an email should not be start with "." ] xxxxx()*@gmail.com [ here the regular expression only allows character, digit, underscore and dash ] xxxx..1234@yahoo.com [double dots are not allowed </pre> **javascript mail code** function ValidateEmail(inputText) { var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; if(inputText.value.match(mailformat)) { document.form1.text1.focus(); return true; } else { alert("You have entered an invalid email address!"); document.form1.text1.focus(); return false; } }
the best one :D (RFC-friendly & no error "too complex") :
function isMail(mail) { pattuser = /^([A-Z0-9_%+\-!#$&'*\/=?^`{|}~]+\.?)*[A-Z0-9_%+\-!#$&'*\/=?^`{|}~]+$/i; pattdomain = /^([A-Z0-9-]+\.?)*[A-Z0-9-]+(\.[A-Z]{2,9})+$/i; tab = mail.split("@"); if (tab.length != 2) return false; return (pattuser.test(tab[0]) && pattdomain.test(tab[1])); }
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
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}))';
This question is more dificult to answer than seems at first sight.
There were loads of people around the world looking for "the regex to rule them all" but the truth is that there are tones of email providers.
What's the problem? Well, "a_z%@gmail.com cannot exists but it may exists an address like that through another provider "a__z@provider.com.
Why? According to the RFC: https://en.wikipedia.org/wiki/Email_address#RFC_specification.
I'll take an excerpt to facilitate the lecture:
The local-part of the email address may use any of these ASCII characters: - uppercase and lowercase Latin letters A to Z and a to z; - digits 0 to 9; - special characters !#$%&'*+-/=?^_`{|}~; - dot ., provided that it is not the first or last character unless quoted, and provided also that it does not appear consecutively unless quoted (e.g. John..Doe@example.com is not allowed but "John..Doe"@example.com is allowed);[6] Note that some mail servers wildcard local parts, typically the characters following a plus and less often the characters following a minus, so fred+bah@domain and fred+foo@domain might end up in the same inbox as fred+@domain or even as fred@domain. This can be useful for tagging emails for sorting, see below, and for spam control. Braces { and } are also used in that fashion, although less often. - space and "(),:;<>@[\] characters are allowed with restrictions (they are only allowed inside a quoted string, as described in the paragraph below, and in addition, a backslash or double-quote must be preceded by a backslash); - comments are allowed with parentheses at either end of the local-part; e.g. john.smith(comment)@example.com and (comment)john.smith@example.com are both equivalent to john.smith@example.com.
So, i can own an email address like that:
A__z/J0hn.sm{it!}h_comment@example.com.co
If you try this address i bet it will fail in all or the major part of regex posted all across the net. But remember this address follows the RFC rules so it's fair valid.
Imagine my frustration at not being able to register anywhere checked with those regex!!
The only one who really can validate an email address is the provider of the email address.
How to deal with, so?
It doesn't matter if a user adds a non-valid e-mail in almost all cases. You can rely on HTML 5 input type="email" that is running near to RFC, little chance to fail. HTML5 input type="email" info: https://www.w3.org/TR/2012/WD-html-markup-20121011/input.email.html
For example, this is an RFC valid email:
"very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@strange.example.com
But the html5 validation will tell you that the text before @ must not contain " or () chars for example, which is actually incorrect.
Anyway, you should do this by accepting the email address and sending an email message to that email address, with a code/link the user must visit to confirm validity.
A good practice while doing this is the "enter your e-mail again" input to avoid user typing errors. If this is not enough for you, add a pre-submit modal-window with a title "is this your current e-mail?", then the mail entered by the user inside an h2 tag, you know, to show clearly which e-mail they entered, then a "yes, submit" button.
I know its not regex but any way...
This is example with node and npm package email-existence this is ultimate checking if email exist and if its in the right form :)
This will ping the email if its responding if it got no response it will return false or else true.
function doesEmailExist(email) { var emailExistence = require('email-existence'); return emailExistence.check(email,function (err,status) { if (status) { return status; } else { throw new Error('Email does not exist'); } }); }
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"});
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 are using AngularJS, just add type="email" to the input element:
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'); }
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; } }
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); }
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
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.
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
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.") } }
<input type="email" class="form-control" required="required" placeholder="Email Address" name="Email" id="Email" autocomplete="Email"> <button class="btn-1 shadow-0 full-width" type="button" id="register">Register account</button>
$("#register").click(function(){ var rea = /^[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])?)*$/; var Email = $("#Email").val(); var x = rea.test(Email); if (!x) { alert('Type Your valid Email'); return false; } </script>
Here's a simple regex that would just check for the basic format of an email e.g., X@Y.C:
\S+@\S+\.\S+
Here is the recommended Regex pattern for HTML5 on MDN:
Browsers that support the email input type automatically provide validation to ensure that only text that matches the standard format for Internet e-mail addresses is entered into the input box. Browsers that implement the specification should be using an algorithm equivalent to the following regular expression:
/^[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])?)*$/
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email#Validation
Here's how I do it. I'm using match() to check for the standard email pattern and I'm adding a class to the input text to notify the user accordingly. Hope that helps!
$(document).ready(function(){ $('#submit').on('click', function(){ var email = $('#email').val(); var pat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; if (email.match(pat)){ $('#email') .addClass('input-valid'); return false; } else { $('#email') .addClass('input-error') .val(''); return false; } }); });
.input-error { border: 1px solid red; color: red; } .input-valid { border: 1px solid green; color: green; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form> <input type="text" id="email" placeholder="name@service.xx" class=""> <input type="submit" id="submit" value="Send"/> </form>
Search for the @ sign in the input field.