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?
-
23@Alex The reason I added this comment is that the suggested regex in the accepted answer will not allow existing live email addresses which is a bad start for a customer, and the really big problem is that even IF the address was accepted it still does not say if it works. The only way to reliably verify that a supplied email is a working valid email is to send a mail with a verification link. So, if your use case does not demand that you verify the email, just do a minimal test for @, otherwise use a verification email. Regex will only provide bad user experience.– David MårtenssonCommented May 3, 2021 at 14:56
-
@David Mårtensson I added a + on your thoughts. However I do think that a verification email-link thing also can be bad user experience. One that can make you lose a customer.– mikael1000Commented Jun 3, 2021 at 10:22
-
7@mikael1000 Sure, but what is the purpose of a regex validation when you will not know if its a valid email anyway. If you do not want to intrude on the customer with a validation link just do the most simple validation <something> at <something> and leave it at that. It will ensure that the customer at least added something that might be an email, anything more it mostly a waste of code until you get to actually validating. You could possibly check if the domain exists with a dns lookup.– David MårtenssonCommented Jun 4, 2021 at 14:23
-
2Very similar: How can I validate an email address using a regular expression?– Peter MortensenCommented Feb 16, 2022 at 23:18
-
3I have to admit, I don't understand why there's some much validation going on when you can't predict if the user made a basic type using the valid characters anyway. Just a check for @ and at least one dot is enough at the start.– Watts EphersonCommented Aug 23, 2022 at 10:56
79 Answers
Using regular expressions is probably the best way of validating an email address in JavaScript. View a bunch of tests on JSFiddle 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,}))$/
);
};
The following is an example of a regular expression that accepts unicode.
const re =
/^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
Keep in mind that one should not rely on JavaScript validation alone, as JavaScript can be easily disabled by the client. Furthermore, it is important to validate on the server side.
The following snippet of code is an example of JavaScript validating an email address on the client side.
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 invalid.');
$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 email address</label>
<input id="email" type="email">
<p id="result"></p>
-
722This regex eliminates valid, in-use emails. Do not use. Google for "RFC822" or "RFC2822" to get a proper regex. Commented Sep 8, 2010 at 2:34
-
74This doesn't even accept the examples in RFC 822. Some simple cases it doesn't match a\@[email protected], a(b)@c.com. See the RFC for more. Here's a regex that won't reject any valid addresses [^@]+@[^@]+\.[^@]+ and protects against common errors.– VrooCommented Oct 26, 2012 at 6:32
-
233You cannot validate email addresses, period. The only one who can validate an email address is the provider of the email address. For example, this answer says these email addresses:
%[email protected], "%2"@gmail.com, "a..b"@gmail.com, "a_b"@gmail.com, [email protected], [email protected] , [email protected]
are all valid, but Gmail will never allow any of these email addresses. 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. Commented Feb 1, 2014 at 8:49 -
21@KevinFegan let's be realistic: you would not be using JavaScript to confirm whether an e-mail is authentic. I see this validation as perfectly reasonable when a user signs up. You probably do not want to bother sending verification e-mails to addresses that cannot possibly exist. Some might also have outbound e-mail limits, making it north worth it to send e-mails to
email@localhost
,i don't have an email
or any other funny user inputs. Commented Jul 16, 2021 at 23:02 -
1@KevinFegan You can't validate an email address, but you can recognise obviously invalid ones. Basically anything that will stop your outgoing mail server from even attempting to send the message. Commented Aug 16, 2021 at 6:35
I've slightly modified Jaymon's answer for people who want really simple validation in the form of:
[email protected]
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 [email protected]')); // true
console.log(validateEmail('my email is anystring@anystring .any')); // false
-
122You can implement something 20x as long that might cause problems for a few users and might not be valid in the future, or you can grab ImmortalFirefly's version to make sure they at least put in the effort to make it look real. Depending on your application it may be more likely to come across someone will get mad because you don't accept their unconventional email, rather than someone who causes problems by entering email addresses that don't really exist (which they can do anyways by entering a 100% valid RFC2822 email address but using an unregistered username or domain). Upvoted! Commented Jul 30, 2012 at 18:20
-
134@ImmortalFirefly, the regex you provided will actually match
name@[email protected]
. Try pasting your line into a JavaScript console. I believe your intention was to match only the entire text, which would require the beginning of text '^' and end of text '$' operators. The one I'm using is/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test('name@[email protected]')
Commented Aug 9, 2012 at 14:58 -
9Emails can contain multiple
@
signs (as comments), also an email doesn't have to contain a period.– ruoholaCommented Oct 6, 2021 at 14:08 -
4@JoseG. Yes. E.g.
http://ai
is someone's valid domain, so they could use e.g.a@ai
as their email.– ruoholaCommented Feb 10, 2022 at 9:42 -
1@Timo
[^\s@]
means "neither a whitespace character nor@
".[xyz]
means any one of x, y or z, and[^xyz]
means any one character except x, y or z.\s
means "any whitespace character".\S
means "any character that is not whitespace".– JelabyCommented Aug 21, 2022 at 11:03
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
[email protected]
. 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
-
111NB: "In actual use today" may have been valid when the code was written, back in 200x. The code will likely remain in use beyond that specific year. (If I had a dime for every "meh, no one will ever use a 4+-letter TLD except those specific ones" I had to fix, I could corner the world's copper and nickel market ;)) Commented Jun 13, 2012 at 15:51
-
6Note that this doesn't catch some valid email addresses, like these emoji ones: mailoji.com Commented Oct 6, 2021 at 1:28
-
10@Toastrackenigma if someone is using an emoji email doesn't deserve to subscribe to my website. As easy as that. Commented Jun 6, 2022 at 13:24
-
@ChristianVincenzoTraina the last one rejects my e-mail address on a .rocks domain. if this stops me from your newsletter then maybe it's good for me that I don't get Ignorant Daily to my inbox, but a list of services stopping me from using this domain includes: country-wide public transport system, an airline, medical services, ...– lnlCommented Apr 23, 2023 at 13:42
-
2@lnl the last one is just unmaintainable. The number of top-level domains exploded since 2009 Commented Apr 23, 2023 at 23:18
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+$/
-
120+1 as sending email and seeing what happens is the only real sure way to validate an email address , theres no need to do more than a simple regex match. Commented Jul 19, 2012 at 7:14
-
4But it won't accept "Mohit Atray"@gmail.com because it contains space character. Maybe we should just use /^\S.*@\S+$/ regex. Commented Jul 8, 2021 at 19:57
-
1That's still not valid. Spaces are permitted in the local-part as long as they are properly escaped (in double quotes). Commented Jun 21, 2022 at 22:10
-
@RandalSchwartz your comment regarding whitespaces before @ is already written by mohit I think.– TimoCommented Aug 22, 2022 at 19:24
-
How to add
{2,6}
to make sure the string after the period is between 2 and 6 chars long?– AvatarCommented Aug 30, 2023 at 4:06
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.
-
77@kommradHomer -- a "regex invalid" address is almost always valid, because whatever regex you use to validate an email address is almost certainly wrong and will exclude valid email addresses. An email address is
name_part@domain_part
and practically anything, including an@
, is valid in the name_part; The addressfoo@[email protected]
is legal, although it must be escaped asfoo\@bar@machine....
. Once the email reaches the domain e.g. 'example.com' that domain can route the mail "locally" so "strange" usernames and hostnames can exist. Commented Mar 7, 2013 at 1:40
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="[email protected]" required>
</label>
<input type="submit">
</form>
jsFiddle link
From the HTML5 spec:
A valid e-mail address is a string that matches the
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])?)*$/
-
54this is good, but the problem with this is that it must be inside a
form
tag and submitted by asubmit
input, which not everyone has the luxury of doing. Also, you can't really style the error message.– JasonCommented Nov 12, 2011 at 0:08 -
At first I found this answer useful, but I tried with some invalid email address and the regex said there were valid... by example :
bar@domain
(extension is missing),A@b@[email protected]
(multiple @) and so on (cf en.wikipedia.org/wiki/Email_address#Examples). I found a nice regex here: emailregex.com Commented Oct 22, 2021 at 15:30 -
2@ThomasChampion Multiple "@" IS valid. First point is valid though.– KNPCommented Dec 6, 2021 at 18:26
-
2@KNP Multiple
@
is valid only if the extra "@" appear in username part and is wrapped in double quote. It seems that also the second point (missing extension) is not valid anymore since 2013 (icann.org/en/announcements/details/…), but yes it depends, I guess someone could consider extension optional. Finally, I choose the moduleaddress
from joi: joi.dev/module/address/api/?v=4.1.0#emailisvalidemail-options to validate email addresss in my app. Commented Dec 7, 2021 at 21:37 -
1This is wrong, you can change the markup from the inspector and bypass the validation. It should be done only for the ux, but its not enough on its own Commented Dec 14, 2023 at 11:19
I have found this to be the best solution:
/^[^\s@]+@[^\s@]+\.[^\s@]+$/
It allows the following formats:
1. [email protected] 2. [email protected] 3. [email protected] 4. [email protected] 9. #!$%&'*+-/=?^_`{}|[email protected] 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 [email protected] format. It will block spaces which are technically allowed by RFC, but they are so rare that I'm happy to do this.
-
This will pass the email "asd@asd..". Shouldn't the TLD be at least 2 characters, and not a dot?– FrexuzCommented Dec 11, 2023 at 8:16
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.
-
8This should be the accepted answer by a long shot. Let browser vendors with on staff regex gurus maintain massively complicated regexes for email addresses. Your average frontend dev building a form for collecting email does not often have time to master verbose regex. Yes you have to rely on the regex the vendor provides, but if you need something more complex, do it on the server and or send an actual email and check the response– MattCommented Jul 16, 2021 at 11:04
-
This is the almost perfect solution. Only little thing that should be added is a check for empty field. HTML5 'email' type accepts an empty string as a valid input. Commented Dec 31, 2021 at 23:00
-
4I might repeat myself, but have you noticed the
input.required = true;
line?– BoldewynCommented Jan 30, 2022 at 13:18 -
1Also worth thinking about: It's robust against future changes, as it doesn't hard-code the actual regex. I like this aspect.– oelnaCommented Apr 10, 2022 at 14:45
-
2What @KarlStephen said. Think of a web app for an intranet application. A browser rejecting e-mail addresses like
user@localhost
would be worse than useless. It would actively hinder the correct fill-out of the form.– BoldewynCommented Sep 19, 2022 at 23:20
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)>)$
-
3@Kato: It uses some incompatible extensions, including
(?>
to stop backtracking and(?<angle><)…(?(angle)>)
to avoid providing a lengthy|
.– Ry- ♦Commented Mar 9, 2014 at 20:05 -
1The
match
method returns an array, thetest
method, which returns a boolean, would be better for this situation.– iPzardCommented Nov 7, 2020 at 20:43
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.
-
23what if there will be more than one '@' symbol? other restricted symbols? This validation cannot be trusted... Commented Apr 26, 2015 at 10:14
-
-
4Its better than most, yes you could have more than one @ with this, but that could also be a valid email like "@"@mydomain.jskd or elldffs(this is @ comment)@mydomain.kjfdij. Both are syntactically valid emails Commented Feb 16, 2021 at 18:37
-
2
-
2@iwazovsky If you're using string-level validation to determine whether you can "trust" the email entered, you're already doing it wrong. Using it for anything other than catching mistakes is a lost cause, and most mistakes that don't get caught by this are going to be something that no regex can catch anyway because they'll probably still look like a valid email. Commented Jan 20, 2022 at 0:38
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[email protected]
.(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);
}
-
-
-
-
@ruohola it has not top-level domain (separated by periods) datatracker.ietf.org/doc/html/rfc3696– pmirandaCommented Sep 29, 2021 at 11:59
-
3@pmiranda E.g.
http://ai
is someone's valid domain, so they could use e.g.a@ai
as their email.– ruoholaCommented Sep 29, 2021 at 12:40
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('[email protected]') );
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?
-
1
-
4@GautamParmar gmail and others ignore symbols; mail sent to [email protected] would end up in [email protected]'s email inbox.– TylerHCommented May 4, 2022 at 13:20
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.
-
This one is easiest solution, we can also use external library like email validator to makes things easier, as mentioned here qawithexperts.com/article/javascript/…– user13993546Commented Jan 22, 2022 at 12:02
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...
-
27This allows the entry of so many invalid email addresses it is useless advice.– cazlabCommented Jan 6, 2012 at 23:07
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('[email protected]') // Return true
validMail('[email protected].') // Return true
validMail('[email protected]') // Return true
validMail('user@localserver') // Return true
validMail('[email protected]') // Return true
validMail('user+mailbox/[email protected]') // Return true
validMail('"very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@strange.example.com') // Return true
validMail('!#$%&\'*+-/=?^_`.{|}[email protected]') // 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@[email protected]') // Return false
validMail('a"b(c)d,e:f;g<h>i[j\k][email protected]') // Return false
validMail('just"not"[email protected]') // Return false
validMail('this is"not\[email protected]') // Return false
validMail('this\ still\"not\\[email protected]') // Return false
validMail('[email protected]') // Return false
validMail('[email protected]') // Return false
Show this test : https://regex101.com/r/LHJ9gU/1
-
This address "abc@example" shall return false, but it return true. The wiki page mentioned that: "it must match the requirements for a hostname" en.wikipedia.org/wiki/Email_address#Domain– Brian HoCommented Sep 16, 2022 at 2:23
-
Regex updated! try this
let val = '[email protected]';
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
-
I don't see this as useful at all for much of the world--and a non-trivial audience for many customers. It fails for internationalized usernames and domains. My answer below addresses this using the URL interface which already has support built into most runtimes. ref: stackoverflow.com/a/72018404/965666– jimmontCommented Jul 26, 2022 at 1:08
-
Maybe make the regex case insensitive. Otherwise it will fail the email address with the uppercase characters.– Brian HoCommented Sep 16, 2022 at 2:52
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 [email protected]
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('[email protected]')){ 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('[email protected]'); // Returns false
check_email(' [email protected]'); // Returns false
check_email('[email protected]'); // Returns true
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
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])+
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.
Wow, there are a lot of answers that contain slightly different regular expressions. I've tried many that I've got different results and a variety of different issues with all of them.
For UI validation, I'm good with the most basic check of looking for an @ sign. It's important to note, that I always do server-side validation with a standard "validate email" that contains a unique link for the user to confirm their email address.
if (email.indexOf('@') > 0)
I have purposely chosen 0 even with zero-based as it also ensures there is a single character before the @.