regex email with angled brackets [duplicate] - javascript

This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
I'd like to check if the user input is an email address in JavaScript, before sending it to a server or attempting to send an email to it, to prevent the most basic mistyping. How could I achieve this?

Using regular expressions is probably the best way. You can see a bunch of tests here (taken from chromium)
const validateEmail = (email) => {
return String(email)
.toLowerCase()
.match(
/^(([^<>()[\]\\.,;:\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,}))$/
);
};
Here's the example of a regular expression that accepts unicode:
const 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:
const validateEmail = (email) => {
return email.match(
/^(([^<>()[\]\\.,;:\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,}))$/
);
};
const validate = () => {
const $result = $('#result');
const email = $('#email').val();
$result.text('');
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;
}
$('#email').on('input', validate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="email">Enter an email address: </label>
<input id="email" />
<h2 id="result"></h2>

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+$/
To prevent matching multiple # signs:
/^[^\s#]+#[^\s#]+\.[^\s#]+$/
The above regexes match the whole string, remove the leading and ^ and trailing $ if you want to match anywhere in the string. The example below matches anywhere in the string.
If you do want to match the whole sring, you may want to trim() the string first.
Example JavaScript function:
function validateEmail(email) {
var re = /\S+#\S+\.\S+/;
return re.test(email);
}
console.log(validateEmail('my email is anystring#anystring.any')); // true
console.log(validateEmail('my email is anystring#anystring .any')); // false

Just for completeness, here you have another RFC 2822 compliant regex
The official standard is known as RFC 2822. It describes the syntax that valid email addresses must adhere to. You can (but you shouldn't — read on) implement it with this regular expression:
(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")#(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])
(...) We get a more practical implementation of RFC 2822 if we omit the syntax using double quotes and square brackets. It will still match 99.99% of all email addresses in actual use today.
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?
A further change you could make is to allow any two-letter country code top level domain, and only specific generic top level domains. This regex filters dummy email addresses like asdf#adsf.adsf. You will need to update it as new top-level domains are added.
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum)\b
So even when following official standards, there are still trade-offs to be made. Don't blindly copy regular expressions from online libraries or discussion forums. Always test them on your own data and with your own applications.
Emphasis mine

Wow, there are lots of complexity here. If all you want to do is just catch the most obvious syntax errors, I would do something like this:
^\S+#\S+$
It usually catches the most obvious errors that the user makes and assures that the form is mostly right, which is what JavaScript validation is all about.
EDIT:
We can also check for '.' in the email using
/^\S+#\S+\.\S+$/

There's something you have to understand the second you decide to use a regular expression to validate emails: It's probably not a good idea. Once you have come to terms with that, there are many implementations out there that can get you halfway there, this article sums them up nicely.
In short, however, the only way to be absolutely, positively sure that what the user entered is in fact an email is to actually send an email and see what happens. Other than that it's all just guesses.

HTML5 itself has email validation. If your browser supports HTML5 then you can use the following code.
<form>
<label>Email Address
<input type="email" placeholder="me#example.com" required>
</label>
<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])?)*$/

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.

In modern browsers you can build on top of #Sushil's answer with pure JavaScript and the DOM:
function validateEmail(value) {
var input = document.createElement('input');
input.type = 'email';
input.required = true;
input.value = value;
return typeof input.checkValidity === 'function' ? input.checkValidity() : /\S+#\S+\.\S+/.test(value);
}
I've put together an example in the fiddle http://jsfiddle.net/boldewyn/2b6d5/. Combined with feature detection and the bare-bones validation from Squirtle's Answer, it frees you from the regular expression massacre and does not bork on old browsers.

JavaScript can match a regular expression:
emailAddress.match( / some_regex /);
Here's an RFC22 regular expression for emails:
^((?>[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+\x20*|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*
"\x20*)*(?<angle><))?((?!\.)(?>\.?[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+)+|"((?=[\x01-\x
7f])[^"\\]|\\[\x01-\x7f])*")#(((?!-)[a-zA-Z\d\-]+(?<!-)\.)+[a-zA-Z]{2,}|\[(((?(?<
!\[)\.)(25[0-5]|2[0-4]\d|[01]?\d?\d)){4}|[a-zA-Z\d\-]*[a-zA-Z\d]:((?=[\x01-\x7f])
[^\\\[\]]|\\[\x01-\x7f])+)\])(?(angle)>)$

All email addresses contain an 'at' (i.e. #) symbol. Test that necessary condition:
email.includes('#')
Or, if you need to support IE/older browsers:
email.indexOf('#') > 0
Don't bother with anything more complicated. Even if you could perfectly determine whether an email is RFC-syntactically valid, that wouldn't tell you whether it belongs to the person who supplied it. That's what really matters.
To test that, send a validation message.

Correct validation of email address in compliance with the RFCs is not something that can be achieved with a one-liner regular expression. An article with the best solution I've found in PHP is What is a valid email address?. Obviously, it has been ported to Java. I think the function is too complex to be ported and used in JavaScript. JavaScript/node.js port: https://www.npmjs.com/package/email-addresses.
A good practice is to validate your data on the client, but double-check the validation on the server. With this in mind, you can simply check whether a string looks like a valid email address on the client and perform the strict check on the server.
Here's the JavaScript function I use to check if a string looks like a valid mail address:
function looksLikeMail(str) {
var lastAtPos = str.lastIndexOf('#');
var lastDotPos = str.lastIndexOf('.');
return (lastAtPos < lastDotPos && lastAtPos > 0 && str.indexOf('##') == -1 && lastDotPos > 2 && (str.length - lastDotPos) > 2);
}
Explanation:
lastAtPos < lastDotPos: Last # should be before last . since # cannot be part of server name (as far as I know).
lastAtPos > 0: There should be something (the email username) before the last #.
str.indexOf('##') == -1: There should be no ## in the address. Even if # appears as the last character in email username, it has to be quoted so " would be between that # and the last # in the address.
lastDotPos > 2: There should be at least three characters before the last dot, for example a#b.com.
(str.length - lastDotPos) > 2: There should be enough characters after the last dot to form a two-character domain. I'm not sure if the brackets are necessary.

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

This was stolen from http://codesnippets.joyent.com/posts/show/1917
email = $('email');
filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (filter.test(email.value)) {
// Yay! valid
return true;
}
else
{return false;}

Do this:
^([a-zA-Z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+\/=?^_`{|}~-]+)*#(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)$
It's based on RFC 2822
Test it at https://regex101.com/r/857lzc/1
Often when storing email addresses in the database I make them lowercase and, in practice, regexs can usually be marked case insensitive. In those cases this is slightly shorter:
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?
Here's an example of it being used in JavaScript (with the case insensitive flag i at the end).
var emailCheck=/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i;
console.log( emailCheck.test('some.body#domain.co.uk') );
Note:
Technically some emails can include quotes in the section before the # symbol with escape characters inside the quotes (so your email user can be obnoxious and contain stuff like # and "..." as long as it's written in quotes). NOBODY DOES THIS EVER! It's obsolete. But, it IS included in the true RFC 2822 standard and omitted here.
Note 2:
The beginning of an email (before the # sign) can be case sensitive (via the spec). However, anyone with a case-sensitive email is probably used to having issues, and, in practice, case insensitive is a safe assumption. More info: Are email addresses case sensitive?
More info: http://www.regular-expressions.info/email.html

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.

Simply check out if the entered email address is valid or not using HTML.
<input type="email"/>
There isn't any need to write a function for validation.

You should not use regular expressions to validate an input string to check if it's an email. It's too complicated and would not cover all the cases.
Now since you can only cover 90% of the cases, write something like:
function isPossiblyValidEmail(txt) {
return txt.length > 5 && txt.indexOf('#')>0;
}
You can refine it. For instance, 'aaa#' is valid. But overall you get the gist. And don't get carried away... A simple 90% solution is better than 100% solution that does not work.
The world needs simpler code...

Wikipedia standard mail syntax :
https://en.wikipedia.org/wiki/Email_address#Examples
https://fr.wikipedia.org/wiki/Adresse_%C3%A9lectronique#Syntaxe_exacte
Function :
function validMail(mail)
{
return /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()\.,;\s#\"]+\.{0,1})+([^<>()\.,;:\s#\"]{2,}|[\d\.]+))$/.test(mail);
}
Valid emails :
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 emails :
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

Regex updated! try this
let val = 'email#domain.com';
if(/^[a-z0-9][a-z0-9-_\.]+#([a-z]|[a-z0-9]?[a-z0-9-]+[a-z0-9])\.[a-z0-9]{2,10}(?:\.[a-z]{2,10})?$/.test(val)) {
console.log('passed');
}
typscript version complete
//
export const emailValid = (val:string):boolean => /^[a-z0-9][a-z0-9-_\.]+#([a-z]|[a-z0-9]?[a-z0-9-]+[a-z0-9])\.[a-z0-9]{2,10}(?:\.[a-z]{2,10})?$/.test(val);
more info https://git.io/vhEfc

It's hard to get an email validator 100% correct. The only real way to get it correct would be to send a test email to the account. That said, there are a few basic checks that can help make sure that you're getting something reasonable.
Some things to improve:
Instead of new RegExp, just try writing the regexp out like this:
if (reg.test(/#/))
Second, check to make sure that a period comes after the # sign, and make sure that there are characters between the #s and periods.

This is how node-validator does it:
/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+#(?:(?:(?:[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]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/

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, the only option is to send the users an email.

Use this code inside your validator function:
var emailID = document.forms["formName"]["form element id"].value;
atpos = emailID.indexOf("#");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct email ID")
return false;
}
Else you can use jQuery. Inside rules define:
eMailId: {
required: true,
email: true
}

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

var testresults
function checkemail() {
var str = document.validation.emailcheck.value
var filter = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
if (filter.test(str))
testresults = true
else {
alert("Please input a valid email address!")
testresults = false
}
return (testresults)
}
function checkbae() {
if (document.layers || document.getElementById || document.all)
return checkemail()
else
return true
}
<form name="validation" onSubmit="return checkbae()">
Please input a valid email address:<br />
<input type="text" size=18 name="emailcheck">
<input type="submit" value="Submit">
</form>

My knowledge of regular expressions is not that good. That's why I check the general syntax with a simple regular expression first and check more specific options with other functions afterwards. This may not be not the best technical solution, but this way I'm way more flexible and faster.
The most common errors I've come across are spaces (especially at the beginning and end) and occasionally a double dot.
function check_email(val){
if(!val.match(/\S+#\S+\.\S+/)){ // Jaymon's / Squirtle's solution
// Do something
return false;
}
if( val.indexOf(' ')!=-1 || val.indexOf('..')!=-1){
// Do something
return false;
}
return true;
}
check_email('check#thiscom'); // Returns false
check_email('check#this..com'); // Returns false
check_email(' check#this.com'); // Returns false
check_email('check#this.com'); // Returns true

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

Here is a very good discussion about using regular expressions to validate email addresses; "Comparing E-mail Address Validating Regular Expressions"
Here is the current top expression, that is JavaScript compatible, for reference purposes:
/^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*#([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i

Apparently, that's it:
/^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+#((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i
Taken from http://fightingforalostcause.net/misc/2006/compare-email-regex.php on Oct 1 '10.
But, of course, that's ignoring internationalization.

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 :
http://regexr.com/3f07j
OR regex:
Regex = /(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#[*[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+]*/

Related

Validate an email address

How would I check that a user's email address ends in on of the three
#camel.com, #mel.com, #camelofegypt.com
This is my code so far, it just validates whether or not the user has provided any text
if ($.trim($("#email").val()).length === 0) {
alert('You must provide valid input');
return false;
I want to implement the email address validation into my code.
use the following regex:
var reg=/#(camel|mel|camelofegypt)\.com$/
reg.test(email)
This only validates if you email ends in one of the three above. If you want ot know general email validation, search the web. There are tons of those
As described in the library to regular expressions, it is difficult to truly validate an email address. However, the below taken from the above website will do a good job.
The official standard is known as RFC 2822. It describes the syntax that valid email addresses must adhere to. You can (but you shouldn't--read on) implement it with this regular expression:
(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")#(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])
Simple Regex:
\b[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b
Trade offs of validating email addresses:
Yes, there are a whole bunch of email addresses that my pet regex doesn't match. The most frequently quoted example are addresses on the .museum top level domain, which is longer than the 4 letters my regex allows for the top level domain. I accept this trade-off because the number of people using .museum email addresses is extremely low. I've never had a complaint that the order forms or newsletter subscription forms on the JGsoft websites refused a .museum address (which they would, since they use the above regex to validate the email address).
However, if you just want your specific domain this is definitely a possibility but it is not recommended to deny an email address because it fails these regular expressions.
Taking the above you could simply validate using the following Regex:
\b[A-Z0-9._%+-]+#(camel|mel|camelofegypt)\.com\b
or:
^[A-Z0-9._%+-]+#(camel|mel|camelofegypt)\.com$
The difference between these two regex are simple, the first regex will match an email address contained within a longer string. While the second regular expression will only match if the whole string is the email address.
JavaScript Regex:
/\b[A-Z0-9._%+-]+#(camel|mel|camelofegypt)\.com\b/i
or:
/^[A-Z0-9._%+-]+#(camel|mel|camelofegypt)\.com$/i
Special Note: You should likely allow for case insensitive with your regex using the i parameter since John#CAMEL.com is the same as john#camel.com. Which i've done in the above regex.
function ValidateEmail(email) {
var regex = /^([a-zA-Z0-9_\.\-\+])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
OR
This is a regular-expression email validation comparison that will test a bunch of valid/invalid email address against the regex provided by you in the textarea below.
^((([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])))\.?$
Try out this javascript
function IsEmail(email) {
var regex = /^([a-zA-Z0-9_\.\-\+])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
Try this function,
function validateEmail($email) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if( !emailReg.test( $email ) ) {
return false;
} else {
return true;
}
}
if( !validateEmail(email)) { /* do stuff here */ }
var x=$("#email").val();
var n=x.split("#");
if($.inArray(camel.com,n)!= -1)//checks if camel.com is there in your email address if not the value will be -1 #is not given in front of camel.com because its split after # which means that #will be present before it if camel.com is prescent.
{
}
else
if($.inArray(mel.com,n)!= -1)
{}
else
if($.inArray(camelofegypth.com,n)!= -1)
{}
else
alert("");
using new regex
demo Here
added support for Address tags (+ sign)
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^((([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);
return pattern.test(emailAddress);
};
Note : Keep in mind that no 100% regex email check exists

Regular expression for multiple email addresses

I am working to validate a string of email addresses. This pattern works fine if there is only one email address:
var pattern = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
But if I have two email addresses separated by space or by a newline, then it does not validate. For example:
xyz#abc.com xyz#bbc.com
or
xyz#abc.com
xyz#bbc.com
Can you please tell me what would be a way to do it? I am new to regular expressions.
Help much appreciated! Thanks.
Try this RegEx
/^\s*(?:\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}\b\s*)+$/
In the above image, everything inside Group 1 is what you already had. I have added a word ending and spaces.
It will match "xyz#abc.com", " xyz#bbc.com ", "xyz#abc.com xyz#bbc.com" and email addresses in multiple lines also.
Update
I got the RegEx for Email from http://www.regular-expressions.info/email.html and I have used it in my expression. You can find it below:
/^\s*(?:([A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4})\b\s*)+$/i
Change the ^ and $ anchors to word boundaries, \b.
/\b\w+...{2,3}\b/
You should also note that the actual specification for email addresses is extremely complicated and there are many emails that will fail this test -- for example those with multiple periods in the domain. May be okay for your purposes, but just pointing it out.
try this
function validateEmail(field) {
var regex=/\b[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b/i;
return (regex.test(field)) ? true : false;
}
function validateMultipleEmailsCommaSeparated(value) {
var result = value.split(" ");
for(var i = 0;i < result.length;i++)
if(!validateEmail(result[i]))
return false;
return true;
}
You might consider simply splitting the whole string into an actual array of email addresses, instead of trying to validate the entire thing at once. This has the advantage of allowing you to point out in your validation message which address failed.
uld look like this:
var emailRegex = /^[A-Z0-9._%+-]+#(?:[A-Z0-9-]+\.)+[A-Z]{2,4}$/i; // http://www.regular-expressions.info/email.html
var split = form.emails.value.split(/[\s;,]+/); // split on any combination of whitespace, comma, or semi-colon
for(i in split)
{
email = split[i];
if(!emailRegex.test(email))
{
errMsg += "The to e-mail address ("+email+") is invalid.\n";
}
}
Your best regular expression for multiple emails accepts all special characters
(-*/+;.,<>}{[]||+_!##$%^&*())
Best Regular Expression for multiple emails
/^([A-Z0-9.%+-]+#[A-Z0-9.-]+.[A-Z]{2,6})*([,;][\s]*([A-Z0-9.%+-]+#[A-Z0-9.-]+.[A-Z]{2,6}))*$/i

Email Regular Expression in Javascript [duplicate]

This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
I'd like to check if the user input is an email address in JavaScript, before sending it to a server or attempting to send an email to it, to prevent the most basic mistyping. How could I achieve this?
Using regular expressions is probably the best way. You can see a bunch of tests here (taken from chromium)
const validateEmail = (email) => {
return String(email)
.toLowerCase()
.match(
/^(([^<>()[\]\\.,;:\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,}))$/
);
};
Here's the example of a regular expression that accepts unicode:
const 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:
const validateEmail = (email) => {
return email.match(
/^(([^<>()[\]\\.,;:\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,}))$/
);
};
const validate = () => {
const $result = $('#result');
const email = $('#email').val();
$result.text('');
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;
}
$('#email').on('input', validate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="email">Enter an email address: </label>
<input id="email" />
<h2 id="result"></h2>
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+$/
To prevent matching multiple # signs:
/^[^\s#]+#[^\s#]+\.[^\s#]+$/
The above regexes match the whole string, remove the leading and ^ and trailing $ if you want to match anywhere in the string. The example below matches anywhere in the string.
If you do want to match the whole sring, you may want to trim() the string first.
Example JavaScript function:
function validateEmail(email) {
var re = /\S+#\S+\.\S+/;
return re.test(email);
}
console.log(validateEmail('my email is anystring#anystring.any')); // true
console.log(validateEmail('my email is anystring#anystring .any')); // false
Just for completeness, here you have another RFC 2822 compliant regex
The official standard is known as RFC 2822. It describes the syntax that valid email addresses must adhere to. You can (but you shouldn't — read on) implement it with this regular expression:
(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")#(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])
(...) We get a more practical implementation of RFC 2822 if we omit the syntax using double quotes and square brackets. It will still match 99.99% of all email addresses in actual use today.
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?
A further change you could make is to allow any two-letter country code top level domain, and only specific generic top level domains. This regex filters dummy email addresses like asdf#adsf.adsf. You will need to update it as new top-level domains are added.
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum)\b
So even when following official standards, there are still trade-offs to be made. Don't blindly copy regular expressions from online libraries or discussion forums. Always test them on your own data and with your own applications.
Emphasis mine
Wow, there are lots of complexity here. If all you want to do is just catch the most obvious syntax errors, I would do something like this:
^\S+#\S+$
It usually catches the most obvious errors that the user makes and assures that the form is mostly right, which is what JavaScript validation is all about.
EDIT:
We can also check for '.' in the email using
/^\S+#\S+\.\S+$/
There's something you have to understand the second you decide to use a regular expression to validate emails: It's probably not a good idea. Once you have come to terms with that, there are many implementations out there that can get you halfway there, this article sums them up nicely.
In short, however, the only way to be absolutely, positively sure that what the user entered is in fact an email is to actually send an email and see what happens. Other than that it's all just guesses.
HTML5 itself has email validation. If your browser supports HTML5 then you can use the following code.
<form>
<label>Email Address
<input type="email" placeholder="me#example.com" required>
</label>
<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])?)*$/
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.
In modern browsers you can build on top of #Sushil's answer with pure JavaScript and the DOM:
function validateEmail(value) {
var input = document.createElement('input');
input.type = 'email';
input.required = true;
input.value = value;
return typeof input.checkValidity === 'function' ? input.checkValidity() : /\S+#\S+\.\S+/.test(value);
}
I've put together an example in the fiddle http://jsfiddle.net/boldewyn/2b6d5/. Combined with feature detection and the bare-bones validation from Squirtle's Answer, it frees you from the regular expression massacre and does not bork on old browsers.
JavaScript can match a regular expression:
emailAddress.match( / some_regex /);
Here's an RFC22 regular expression for emails:
^((?>[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+\x20*|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*
"\x20*)*(?<angle><))?((?!\.)(?>\.?[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+)+|"((?=[\x01-\x
7f])[^"\\]|\\[\x01-\x7f])*")#(((?!-)[a-zA-Z\d\-]+(?<!-)\.)+[a-zA-Z]{2,}|\[(((?(?<
!\[)\.)(25[0-5]|2[0-4]\d|[01]?\d?\d)){4}|[a-zA-Z\d\-]*[a-zA-Z\d]:((?=[\x01-\x7f])
[^\\\[\]]|\\[\x01-\x7f])+)\])(?(angle)>)$
All email addresses contain an 'at' (i.e. #) symbol. Test that necessary condition:
email.includes('#')
Or, if you need to support IE/older browsers:
email.indexOf('#') > 0
Don't bother with anything more complicated. Even if you could perfectly determine whether an email is RFC-syntactically valid, that wouldn't tell you whether it belongs to the person who supplied it. That's what really matters.
To test that, send a validation message.
Correct validation of email address in compliance with the RFCs is not something that can be achieved with a one-liner regular expression. An article with the best solution I've found in PHP is What is a valid email address?. Obviously, it has been ported to Java. I think the function is too complex to be ported and used in JavaScript. JavaScript/node.js port: https://www.npmjs.com/package/email-addresses.
A good practice is to validate your data on the client, but double-check the validation on the server. With this in mind, you can simply check whether a string looks like a valid email address on the client and perform the strict check on the server.
Here's the JavaScript function I use to check if a string looks like a valid mail address:
function looksLikeMail(str) {
var lastAtPos = str.lastIndexOf('#');
var lastDotPos = str.lastIndexOf('.');
return (lastAtPos < lastDotPos && lastAtPos > 0 && str.indexOf('##') == -1 && lastDotPos > 2 && (str.length - lastDotPos) > 2);
}
Explanation:
lastAtPos < lastDotPos: Last # should be before last . since # cannot be part of server name (as far as I know).
lastAtPos > 0: There should be something (the email username) before the last #.
str.indexOf('##') == -1: There should be no ## in the address. Even if # appears as the last character in email username, it has to be quoted so " would be between that # and the last # in the address.
lastDotPos > 2: There should be at least three characters before the last dot, for example a#b.com.
(str.length - lastDotPos) > 2: There should be enough characters after the last dot to form a two-character domain. I'm not sure if the brackets are necessary.
This is the correct RFC822 version.
function checkEmail(emailAddress) {
var sQtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]';
var sDtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]';
var sAtom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+';
var sQuotedPair = '\\x5c[\\x00-\\x7f]';
var sDomainLiteral = '\\x5b(' + sDtext + '|' + sQuotedPair + ')*\\x5d';
var sQuotedString = '\\x22(' + sQtext + '|' + sQuotedPair + ')*\\x22';
var sDomain_ref = sAtom;
var sSubDomain = '(' + sDomain_ref + '|' + sDomainLiteral + ')';
var sWord = '(' + sAtom + '|' + sQuotedString + ')';
var sDomain = sSubDomain + '(\\x2e' + sSubDomain + ')*';
var sLocalPart = sWord + '(\\x2e' + sWord + ')*';
var sAddrSpec = sLocalPart + '\\x40' + sDomain; // complete RFC822 email address spec
var sValidEmail = '^' + sAddrSpec + '$'; // as whole string
var reValidEmail = new RegExp(sValidEmail);
return reValidEmail.test(emailAddress);
}
This was stolen from http://codesnippets.joyent.com/posts/show/1917
email = $('email');
filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (filter.test(email.value)) {
// Yay! valid
return true;
}
else
{return false;}
Do this:
^([a-zA-Z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+\/=?^_`{|}~-]+)*#(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)$
It's based on RFC 2822
Test it at https://regex101.com/r/857lzc/1
Often when storing email addresses in the database I make them lowercase and, in practice, regexs can usually be marked case insensitive. In those cases this is slightly shorter:
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?
Here's an example of it being used in JavaScript (with the case insensitive flag i at the end).
var emailCheck=/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i;
console.log( emailCheck.test('some.body#domain.co.uk') );
Note:
Technically some emails can include quotes in the section before the # symbol with escape characters inside the quotes (so your email user can be obnoxious and contain stuff like # and "..." as long as it's written in quotes). NOBODY DOES THIS EVER! It's obsolete. But, it IS included in the true RFC 2822 standard and omitted here.
Note 2:
The beginning of an email (before the # sign) can be case sensitive (via the spec). However, anyone with a case-sensitive email is probably used to having issues, and, in practice, case insensitive is a safe assumption. More info: Are email addresses case sensitive?
More info: http://www.regular-expressions.info/email.html
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.
Simply check out if the entered email address is valid or not using HTML.
<input type="email"/>
There isn't any need to write a function for validation.
You should not use regular expressions to validate an input string to check if it's an email. It's too complicated and would not cover all the cases.
Now since you can only cover 90% of the cases, write something like:
function isPossiblyValidEmail(txt) {
return txt.length > 5 && txt.indexOf('#')>0;
}
You can refine it. For instance, 'aaa#' is valid. But overall you get the gist. And don't get carried away... A simple 90% solution is better than 100% solution that does not work.
The world needs simpler code...
Wikipedia standard mail syntax :
https://en.wikipedia.org/wiki/Email_address#Examples
https://fr.wikipedia.org/wiki/Adresse_%C3%A9lectronique#Syntaxe_exacte
Function :
function validMail(mail)
{
return /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()\.,;\s#\"]+\.{0,1})+([^<>()\.,;:\s#\"]{2,}|[\d\.]+))$/.test(mail);
}
Valid emails :
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 emails :
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
Regex updated! try this
let val = 'email#domain.com';
if(/^[a-z0-9][a-z0-9-_\.]+#([a-z]|[a-z0-9]?[a-z0-9-]+[a-z0-9])\.[a-z0-9]{2,10}(?:\.[a-z]{2,10})?$/.test(val)) {
console.log('passed');
}
typscript version complete
//
export const emailValid = (val:string):boolean => /^[a-z0-9][a-z0-9-_\.]+#([a-z]|[a-z0-9]?[a-z0-9-]+[a-z0-9])\.[a-z0-9]{2,10}(?:\.[a-z]{2,10})?$/.test(val);
more info https://git.io/vhEfc
It's hard to get an email validator 100% correct. The only real way to get it correct would be to send a test email to the account. That said, there are a few basic checks that can help make sure that you're getting something reasonable.
Some things to improve:
Instead of new RegExp, just try writing the regexp out like this:
if (reg.test(/#/))
Second, check to make sure that a period comes after the # sign, and make sure that there are characters between the #s and periods.
This is how node-validator does it:
/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+#(?:(?:(?:[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]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/
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, the only option is to send the users an email.
Use this code inside your validator function:
var emailID = document.forms["formName"]["form element id"].value;
atpos = emailID.indexOf("#");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct email ID")
return false;
}
Else you can use jQuery. Inside rules define:
eMailId: {
required: true,
email: true
}
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'); }
var testresults
function checkemail() {
var str = document.validation.emailcheck.value
var filter = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
if (filter.test(str))
testresults = true
else {
alert("Please input a valid email address!")
testresults = false
}
return (testresults)
}
function checkbae() {
if (document.layers || document.getElementById || document.all)
return checkemail()
else
return true
}
<form name="validation" onSubmit="return checkbae()">
Please input a valid email address:<br />
<input type="text" size=18 name="emailcheck">
<input type="submit" value="Submit">
</form>
My knowledge of regular expressions is not that good. That's why I check the general syntax with a simple regular expression first and check more specific options with other functions afterwards. This may not be not the best technical solution, but this way I'm way more flexible and faster.
The most common errors I've come across are spaces (especially at the beginning and end) and occasionally a double dot.
function check_email(val){
if(!val.match(/\S+#\S+\.\S+/)){ // Jaymon's / Squirtle's solution
// Do something
return false;
}
if( val.indexOf(' ')!=-1 || val.indexOf('..')!=-1){
// Do something
return false;
}
return true;
}
check_email('check#thiscom'); // Returns false
check_email('check#this..com'); // Returns false
check_email(' check#this.com'); // Returns false
check_email('check#this.com'); // Returns true
Regex for validating email address
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])+
Here is a very good discussion about using regular expressions to validate email addresses; "Comparing E-mail Address Validating Regular Expressions"
Here is the current top expression, that is JavaScript compatible, for reference purposes:
/^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*#([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i
Apparently, that's it:
/^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+#((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i
Taken from http://fightingforalostcause.net/misc/2006/compare-email-regex.php on Oct 1 '10.
But, of course, that's ignoring internationalization.
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 :
http://regexr.com/3f07j
OR regex:
Regex = /(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#[*[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+]*/

Email validation not accepting domains with only two characters

I am working with an email validation script and all is well, apart from if a user tries to enter an address with only two characters in the domain such as test#me.com or temp#ip.com
The validation then fires an error, I have looked through but cant see where this behaviour is being targeted, the code is below...
function validate_youremail()
{
var isvalidemailflag = 0;
if(jQuery("#property_mail_email").val() == '')
{
isvalidemailflag = 1;
}else
if(jQuery("#property_mail_email").val() != '')
{
var a = jQuery("#property_mail_email").val();
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
//if it's valid email
if(filter.test(a)){
isvalidemailflag = 0;
}else{
isvalidemailflag = 1;
}
}
if(isvalidemailflag)
{
youremail.addClass("error");
youremailInfo.text("Please Enter valid Email Address");
youremailInfo.addClass("message_error2");
return false;
}else
{
youremail.removeClass("error");
youremailInfo.text("");
youremailInfo.removeClass("message_error");
return true;
}
Its probably staring me straight in the face but its been a long day :) Can anyone point me in the right direction?
#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+
Means "#" then "one or more of those characters" then "one or more of those characters and dots and hyphens" then "one or more of those characters".
That makes it "at least three characters".
You probably want to change the middle part (of that snippet) to be zero or more (i.e. * instead of +).
The expression is still broken though. The problem that jumps out at me is that it rejects email addresses with a + in the part before the #.
Email Validation as per RFC2822 standards.
Pattern: /[a-z0-9!#$%&'*+/=?^_{|}~-]+(?:.[a-z0-9!#$%&'*+/=?^_{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/g
Source: RegExr
Mind you, the RFC2822 standard doesn't allow upper case characters in an email address, but you can easily adapt it for your own purposes.
I recommend you to use another regular expression.
This regular expression has been extracted from the PHP source code written in C.
/^(?!(?:(?:\x22?\x5C[\x00-\x7E]\x22?)|(?:\x22?[^\x5C\x22]\x22?)){255,})(?!(?:(?:\x22?\x5C[\x00-\x7E]\x22?)|(?:\x22?[^\x5C\x22]\x22?)){65,}#)(?:(?:[\x21\x23-\x27\x2A\x2B\x2D\x2F-\x39\x3D\x3F\x5E-\x7E]+)|(?:\x22(?:[\x01-\x08\x0B\x0C\x0E-\x1F\x21\x23-\x5B\x5D-\x7F]|(?:\x5C[\x00-\x7F]))*\x22))(?:\.(?:(?:[\x21\x23-\x27\x2A\x2B\x2D\x2F-\x39\x3D\x3F\x5E-\x7E]+)|(?:\x22(?:[\x01-\x08\x0B\x0C\x0E-\x1F\x21\x23-\x5B\x5D-\x7F]|(?:\x5C[\x00-\x7F]))*\x22)))*#(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-+[a-z0-9]+)*\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-+[a-z0-9]+)*)|(?:\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\]))$/i
.test('temp#ip.com');

How can I validate an email address in JavaScript?

This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
I'd like to check if the user input is an email address in JavaScript, before sending it to a server or attempting to send an email to it, to prevent the most basic mistyping. How could I achieve this?
Using regular expressions is probably the best way. You can see a bunch of tests here (taken from chromium)
const validateEmail = (email) => {
return String(email)
.toLowerCase()
.match(
/^(([^<>()[\]\\.,;:\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,}))$/
);
};
Here's the example of a regular expression that accepts unicode:
const 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:
const validateEmail = (email) => {
return email.match(
/^(([^<>()[\]\\.,;:\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,}))$/
);
};
const validate = () => {
const $result = $('#result');
const email = $('#email').val();
$result.text('');
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;
}
$('#email').on('input', validate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="email">Enter an email address: </label>
<input id="email" />
<h2 id="result"></h2>
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+$/
To prevent matching multiple # signs:
/^[^\s#]+#[^\s#]+\.[^\s#]+$/
The above regexes match the whole string, remove the leading and ^ and trailing $ if you want to match anywhere in the string. The example below matches anywhere in the string.
If you do want to match the whole sring, you may want to trim() the string first.
Example JavaScript function:
function validateEmail(email) {
var re = /\S+#\S+\.\S+/;
return re.test(email);
}
console.log(validateEmail('my email is anystring#anystring.any')); // true
console.log(validateEmail('my email is anystring#anystring .any')); // false
Just for completeness, here you have another RFC 2822 compliant regex
The official standard is known as RFC 2822. It describes the syntax that valid email addresses must adhere to. You can (but you shouldn't — read on) implement it with this regular expression:
(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")#(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])
(...) We get a more practical implementation of RFC 2822 if we omit the syntax using double quotes and square brackets. It will still match 99.99% of all email addresses in actual use today.
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?
A further change you could make is to allow any two-letter country code top level domain, and only specific generic top level domains. This regex filters dummy email addresses like asdf#adsf.adsf. You will need to update it as new top-level domains are added.
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum)\b
So even when following official standards, there are still trade-offs to be made. Don't blindly copy regular expressions from online libraries or discussion forums. Always test them on your own data and with your own applications.
Emphasis mine
Wow, there are lots of complexity here. If all you want to do is just catch the most obvious syntax errors, I would do something like this:
^\S+#\S+$
It usually catches the most obvious errors that the user makes and assures that the form is mostly right, which is what JavaScript validation is all about.
EDIT:
We can also check for '.' in the email using
/^\S+#\S+\.\S+$/
There's something you have to understand the second you decide to use a regular expression to validate emails: It's probably not a good idea. Once you have come to terms with that, there are many implementations out there that can get you halfway there, this article sums them up nicely.
In short, however, the only way to be absolutely, positively sure that what the user entered is in fact an email is to actually send an email and see what happens. Other than that it's all just guesses.
HTML5 itself has email validation. If your browser supports HTML5 then you can use the following code.
<form>
<label>Email Address
<input type="email" placeholder="me#example.com" required>
</label>
<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])?)*$/
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.
In modern browsers you can build on top of #Sushil's answer with pure JavaScript and the DOM:
function validateEmail(value) {
var input = document.createElement('input');
input.type = 'email';
input.required = true;
input.value = value;
return typeof input.checkValidity === 'function' ? input.checkValidity() : /\S+#\S+\.\S+/.test(value);
}
I've put together an example in the fiddle http://jsfiddle.net/boldewyn/2b6d5/. Combined with feature detection and the bare-bones validation from Squirtle's Answer, it frees you from the regular expression massacre and does not bork on old browsers.
JavaScript can match a regular expression:
emailAddress.match( / some_regex /);
Here's an RFC22 regular expression for emails:
^((?>[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+\x20*|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*
"\x20*)*(?<angle><))?((?!\.)(?>\.?[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+)+|"((?=[\x01-\x
7f])[^"\\]|\\[\x01-\x7f])*")#(((?!-)[a-zA-Z\d\-]+(?<!-)\.)+[a-zA-Z]{2,}|\[(((?(?<
!\[)\.)(25[0-5]|2[0-4]\d|[01]?\d?\d)){4}|[a-zA-Z\d\-]*[a-zA-Z\d]:((?=[\x01-\x7f])
[^\\\[\]]|\\[\x01-\x7f])+)\])(?(angle)>)$
All email addresses contain an 'at' (i.e. #) symbol. Test that necessary condition:
email.includes('#')
Or, if you need to support IE/older browsers:
email.indexOf('#') > 0
Don't bother with anything more complicated. Even if you could perfectly determine whether an email is RFC-syntactically valid, that wouldn't tell you whether it belongs to the person who supplied it. That's what really matters.
To test that, send a validation message.
Correct validation of email address in compliance with the RFCs is not something that can be achieved with a one-liner regular expression. An article with the best solution I've found in PHP is What is a valid email address?. Obviously, it has been ported to Java. I think the function is too complex to be ported and used in JavaScript. JavaScript/node.js port: https://www.npmjs.com/package/email-addresses.
A good practice is to validate your data on the client, but double-check the validation on the server. With this in mind, you can simply check whether a string looks like a valid email address on the client and perform the strict check on the server.
Here's the JavaScript function I use to check if a string looks like a valid mail address:
function looksLikeMail(str) {
var lastAtPos = str.lastIndexOf('#');
var lastDotPos = str.lastIndexOf('.');
return (lastAtPos < lastDotPos && lastAtPos > 0 && str.indexOf('##') == -1 && lastDotPos > 2 && (str.length - lastDotPos) > 2);
}
Explanation:
lastAtPos < lastDotPos: Last # should be before last . since # cannot be part of server name (as far as I know).
lastAtPos > 0: There should be something (the email username) before the last #.
str.indexOf('##') == -1: There should be no ## in the address. Even if # appears as the last character in email username, it has to be quoted so " would be between that # and the last # in the address.
lastDotPos > 2: There should be at least three characters before the last dot, for example a#b.com.
(str.length - lastDotPos) > 2: There should be enough characters after the last dot to form a two-character domain. I'm not sure if the brackets are necessary.
This is the correct RFC822 version.
function checkEmail(emailAddress) {
var sQtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]';
var sDtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]';
var sAtom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+';
var sQuotedPair = '\\x5c[\\x00-\\x7f]';
var sDomainLiteral = '\\x5b(' + sDtext + '|' + sQuotedPair + ')*\\x5d';
var sQuotedString = '\\x22(' + sQtext + '|' + sQuotedPair + ')*\\x22';
var sDomain_ref = sAtom;
var sSubDomain = '(' + sDomain_ref + '|' + sDomainLiteral + ')';
var sWord = '(' + sAtom + '|' + sQuotedString + ')';
var sDomain = sSubDomain + '(\\x2e' + sSubDomain + ')*';
var sLocalPart = sWord + '(\\x2e' + sWord + ')*';
var sAddrSpec = sLocalPart + '\\x40' + sDomain; // complete RFC822 email address spec
var sValidEmail = '^' + sAddrSpec + '$'; // as whole string
var reValidEmail = new RegExp(sValidEmail);
return reValidEmail.test(emailAddress);
}
This was stolen from http://codesnippets.joyent.com/posts/show/1917
email = $('email');
filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (filter.test(email.value)) {
// Yay! valid
return true;
}
else
{return false;}
Do this:
^([a-zA-Z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+\/=?^_`{|}~-]+)*#(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)$
It's based on RFC 2822
Test it at https://regex101.com/r/857lzc/1
Often when storing email addresses in the database I make them lowercase and, in practice, regexs can usually be marked case insensitive. In those cases this is slightly shorter:
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?
Here's an example of it being used in JavaScript (with the case insensitive flag i at the end).
var emailCheck=/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i;
console.log( emailCheck.test('some.body#domain.co.uk') );
Note:
Technically some emails can include quotes in the section before the # symbol with escape characters inside the quotes (so your email user can be obnoxious and contain stuff like # and "..." as long as it's written in quotes). NOBODY DOES THIS EVER! It's obsolete. But, it IS included in the true RFC 2822 standard and omitted here.
Note 2:
The beginning of an email (before the # sign) can be case sensitive (via the spec). However, anyone with a case-sensitive email is probably used to having issues, and, in practice, case insensitive is a safe assumption. More info: Are email addresses case sensitive?
More info: http://www.regular-expressions.info/email.html
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.
Simply check out if the entered email address is valid or not using HTML.
<input type="email"/>
There isn't any need to write a function for validation.
You should not use regular expressions to validate an input string to check if it's an email. It's too complicated and would not cover all the cases.
Now since you can only cover 90% of the cases, write something like:
function isPossiblyValidEmail(txt) {
return txt.length > 5 && txt.indexOf('#')>0;
}
You can refine it. For instance, 'aaa#' is valid. But overall you get the gist. And don't get carried away... A simple 90% solution is better than 100% solution that does not work.
The world needs simpler code...
Wikipedia standard mail syntax :
https://en.wikipedia.org/wiki/Email_address#Examples
https://fr.wikipedia.org/wiki/Adresse_%C3%A9lectronique#Syntaxe_exacte
Function :
function validMail(mail)
{
return /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()\.,;\s#\"]+\.{0,1})+([^<>()\.,;:\s#\"]{2,}|[\d\.]+))$/.test(mail);
}
Valid emails :
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 emails :
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
Regex updated! try this
let val = 'email#domain.com';
if(/^[a-z0-9][a-z0-9-_\.]+#([a-z]|[a-z0-9]?[a-z0-9-]+[a-z0-9])\.[a-z0-9]{2,10}(?:\.[a-z]{2,10})?$/.test(val)) {
console.log('passed');
}
typscript version complete
//
export const emailValid = (val:string):boolean => /^[a-z0-9][a-z0-9-_\.]+#([a-z]|[a-z0-9]?[a-z0-9-]+[a-z0-9])\.[a-z0-9]{2,10}(?:\.[a-z]{2,10})?$/.test(val);
more info https://git.io/vhEfc
It's hard to get an email validator 100% correct. The only real way to get it correct would be to send a test email to the account. That said, there are a few basic checks that can help make sure that you're getting something reasonable.
Some things to improve:
Instead of new RegExp, just try writing the regexp out like this:
if (reg.test(/#/))
Second, check to make sure that a period comes after the # sign, and make sure that there are characters between the #s and periods.
This is how node-validator does it:
/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+#(?:(?:(?:[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]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/
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, the only option is to send the users an email.
Use this code inside your validator function:
var emailID = document.forms["formName"]["form element id"].value;
atpos = emailID.indexOf("#");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct email ID")
return false;
}
Else you can use jQuery. Inside rules define:
eMailId: {
required: true,
email: true
}
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'); }
var testresults
function checkemail() {
var str = document.validation.emailcheck.value
var filter = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
if (filter.test(str))
testresults = true
else {
alert("Please input a valid email address!")
testresults = false
}
return (testresults)
}
function checkbae() {
if (document.layers || document.getElementById || document.all)
return checkemail()
else
return true
}
<form name="validation" onSubmit="return checkbae()">
Please input a valid email address:<br />
<input type="text" size=18 name="emailcheck">
<input type="submit" value="Submit">
</form>
My knowledge of regular expressions is not that good. That's why I check the general syntax with a simple regular expression first and check more specific options with other functions afterwards. This may not be not the best technical solution, but this way I'm way more flexible and faster.
The most common errors I've come across are spaces (especially at the beginning and end) and occasionally a double dot.
function check_email(val){
if(!val.match(/\S+#\S+\.\S+/)){ // Jaymon's / Squirtle's solution
// Do something
return false;
}
if( val.indexOf(' ')!=-1 || val.indexOf('..')!=-1){
// Do something
return false;
}
return true;
}
check_email('check#thiscom'); // Returns false
check_email('check#this..com'); // Returns false
check_email(' check#this.com'); // Returns false
check_email('check#this.com'); // Returns true
Regex for validating email address
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])+
Here is a very good discussion about using regular expressions to validate email addresses; "Comparing E-mail Address Validating Regular Expressions"
Here is the current top expression, that is JavaScript compatible, for reference purposes:
/^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*#([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i
Apparently, that's it:
/^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+#((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i
Taken from http://fightingforalostcause.net/misc/2006/compare-email-regex.php on Oct 1 '10.
But, of course, that's ignoring internationalization.
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 :
http://regexr.com/3f07j
OR regex:
Regex = /(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#[*[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+]*/

Categories