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?
-
15@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årtensson May 03 '21 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. – mikael1000 Jun 03 '21 at 10:22
-
6@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
at – David Mårtensson Jun 04 '21 at 14:23and 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. -
@DavidMårtensson A customer that mistypes one character in her e-mail will have it regexp validated where it still is wrong. The result will be: _no_ communication possible. To me that is the __worst__ user experience one can imagine. A validation confirmation will engage the user in a conversation which shows respect and genuine interest in customers needs. – theking2 Dec 06 '21 at 12:39
-
2Very similar: *[How can I validate an email address using a regular expression?](https://stackoverflow.com/questions/201323/)* – Peter Mortensen Feb 16 '22 at 23:18
-
If this question is to stay open it needs to remove "validation", otherwise it should to closed. – Braiam May 04 '22 at 13:44
-
2This question is being [discussed on meta](https://meta.stackoverflow.com/questions/417847). – cigien May 04 '22 at 16:13
102 Answers
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);
And this is the html:
<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>
- 2,959
- 3
- 15
- 28
- 10,684
- 7
- 27
- 32
-
678This regex eliminates valid, in-use emails. Do not use. Google for "RFC822" or "RFC2822" to get a proper regex. – Randal Schwartz Sep 08 '10 at 02:34
-
66This doesn't even accept the examples in RFC 822. Some simple cases it doesn't match a\@b@c.com, 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. – Vroo Oct 26 '12 at 06:32
-
216You 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: `%2@gmail.com, "%2"@gmail.com, "a..b"@gmail.com, "a_b"@gmail.com, _@gmail.com, 1@gmail.com , 1_example@something.gmail.com` 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. – Kevin Fegan Feb 01 '14 at 08:49
-
8@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. – undefined Jul 16 '21 at 23:02
-
-
@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. – Abhi Beckert Aug 16 '21 at 06:35
-
This kind of email foo@3.com is not validated by the regex from the answer. I've tested this one and it worked: ^[\w.]+@[a-z]+.\w{2,3}$ – Iasmini Gomes Sep 24 '21 at 12:26
-
@lasmini Gomes this regex is hopelessly naive. brian@li is a valid email address. also brian@my.host.amazon.com is also valid. Also brian+123@gmail.com is also valid. And is use A LOT by testers because the +123 is ignored by gmail. – PlexQ Oct 17 '21 at 23:29
-
this is invalid `sean.o'leary@cobbcounty.org` and your code couldn't verify that, It says valid email. – Code Cooker Nov 05 '21 at 09:01
-
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@]+$/
Example JavaScript function:
function validateEmail(email)
{
var re = /\S+@\S+\.\S+/;
return re.test(email);
}
console.log(validateEmail('anystring@anystring.anystring'));
- 4,222
- 1
- 12
- 36
- 3,117
- 2
- 21
- 21
-
100You 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! – user83358 Jul 30 '12 at 18:20
-
124@ImmortalFirefly, the regex you provided will actually match `name@again@example.com`. 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@again@example.com')` – OregonTrail Aug 09 '12 at 14:58
-
The second regexp does not require a top-level domain, i.e. it accepts `user@domain`. But AFAIK this is actually a valid e-mail address, although uncommon. The first regexp requires a TLD, so it doesn't cover these types of addresses. – waldgeist Jul 15 '21 at 13:00
-
5Emails can contain multiple `@` signs (as comments), also an email doesn't have to contain a period. – ruohola Oct 06 '21 at 14:08
-
@ruohola is this also the reason why an email will be valid after you input an @ sign without having any periods after? – Jose G. Feb 10 '22 at 09:10
-
3@JoseG. Yes. E.g. `http://ai` is someone's valid domain, so they could use e.g. `a@ai` as their email. – ruohola Feb 10 '22 at 09:42
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)\bSo 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
- 1
- 1
- 35,226
- 13
- 82
- 97
-
104NB: "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 ;)) – Piskvor left the building Jun 13 '12 at 15:51
-
3Note that this doesn't catch some valid email addresses, like these emoji ones: https://mailoji.com/ – Toastrackenigma Oct 06 '21 at 01:28
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+$/
-
102+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. – kommradHomer Jul 19 '12 at 07:14
-
4But it won't accept "Mohit Atray"@gmail.com because it contains space character. Maybe we should just use /^\S.*@\S+$/ regex. – Mohit Atray Jul 08 '21 at 19:57
-
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.
- 466,948
- 77
- 516
- 433
-
76@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 address `foo@bar@machine.subdomain.example.museum` is legal, although it must be escaped as `foo\@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. – Stephen P Mar 07 '13 at 01:40
HTML5 itself has email validation. If your browser supports HTML5 then you can use the following code.
<form>
<input type="email" placeholder="me@example.com" required>
<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])?)*$/
-
47this is good, but the problem with this is that it must be inside a `form` tag and submitted by a `submit` input, which not everyone has the luxury of doing. Also, you can't really style the error message. – Jason Nov 12 '11 at 00: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@c@example.com` (multiple @) and so on (cf https://en.wikipedia.org/wiki/Email_address#Examples). I found a nice regex here: https://emailregex.com – Thomas Champion Oct 22 '21 at 15:30
-
1
-
1@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 (https://www.icann.org/en/announcements/details/new-gtld-dotless-domain-names-prohibited-30-8-2013-en), but yes it depends, I guess someone could consider extension optional. Finally, I choose the module `address` from joi: https://joi.dev/module/address/api/?v=4.1.0#emailisvalidemail-options to validate email addresss in my app. – Thomas Champion Dec 07 '21 at 21:37
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.
- 3,295
- 5
- 36
- 45
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.
- 78,902
- 44
- 148
- 207
-
3This 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 – Matt Jul 16 '21 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. – NurShomik Dec 31 '21 at 23:00
-
That’s what the `input.required = true;` line should take care of ;-) – Boldewyn Jan 02 '22 at 17:18
-
HTML5 'email' type accepts an empty string incase the field is not requierd. But if user decide to enter the email, it need to be valide. – marcb Jan 29 '22 at 16:49
-
1I might repeat myself, but have you noticed the `input.required = true;` line? – Boldewyn Jan 30 '22 at 13:18
-
Also worth thinking about: It's robust against future changes, as it doesn't hard-code the actual regex. I like this aspect. – oelna Apr 10 '22 at 14:45
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)>)$
- 1
- 1
- 39,872
- 21
- 100
- 136
-
2@Kato: It uses some incompatible extensions, including `(?>` to stop backtracking and `(?
)` to avoid providing a lengthy `|`. – Ry- Mar 09 '14 at 20:05 -
The `match` method returns an array, the `test` method, which returns a boolean, would be better for this situation. – iPzard Nov 07 '20 at 20:43
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);
}
- 2,532
- 1
- 21
- 24
- 6,615
- 11
- 53
- 92
-
-
-
-
@ruohola it has not top-level domain (separated by periods) https://datatracker.ietf.org/doc/html/rfc3696 – pmiranda Sep 29 '21 at 11:59
-
2@pmiranda E.g. `http://ai` is someone's valid domain, so they could use e.g. `a@ai` as their email. – ruohola Sep 29 '21 at 12:40
-
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.
- 19,113
- 6
- 51
- 82
- 126,394
- 80
- 383
- 450
-
21what if there will be more than one '@' symbol? other restricted symbols? This validation cannot be trusted... – iwazovsky Apr 26 '15 at 10:14
-
-
3Its 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 – David Mårtensson Feb 16 '21 at 18:37
-
2
-
1@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. – John Montgomery Jan 20 '22 at 00: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 examplea@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.
- 10,906
- 3
- 38
- 47
- 2,109
- 4
- 23
- 43
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;}
- 792
- 2
- 7
- 14
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?
- 752
- 10
- 15
- 10,951
- 2
- 36
- 33
-
1
-
1@GautamParmar gmail and others ignore symbols; mail sent to gautam+@gmail.com would end up in gautam@gmail.com's email inbox. – TylerH May 04 '22 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.
- 3,641
- 2
- 30
- 33
- 166
- 3
- 8
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.
- 30,030
- 21
- 100
- 124
-
This one is easiest solution, we can also use external library like [email validator](https://www.npmjs.com/package/email-validator) to makes things easier, as mentioned here https://qawithexperts.com/article/javascript/email-validation-using-javascript-with-or-without-regex/317 – Vikram Jan 22 '22 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...
- 13,873
- 17
- 69
- 100
-
26This allows the entry of so many invalid email addresses it is useless advice. – cazlab Jan 06 '12 at 23:07
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.
- 7,659
- 4
- 22
- 36
- 6,728
- 2
- 32
- 35
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])\]))$/
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);
}
Valids mails :
validMail('Abc@example.com') // Return true
validMail('Abc@example.com.') // Return true
validMail('Abc@10.42.0.1') // Return true
validMail('user@localserver') // Return true
validMail('Abc.123@example.com') // Return true
validMail('user+mailbox/department=shipping@example.com') // Return true
validMail('"very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@strange.example.com') // Return true
validMail('!#$%&\'*+-/=?^_`.{|}~@example.com') // Return true
validMail('"()<>[]:,;@\\\"!#$%&\'-/=?^_`{}| ~.a"@example.org') // Return true
validMail('"Abc@def"@example.com') // Return true
validMail('"Fred Bloggs"@example.com') // Return true
validMail('"Joe.\\Blow"@example.com') // Return true
validMail('Loïc.Accentué@voilà.fr') // Return true
validMail('" "@example.org') // Return true
validMail('user@[IPv6:2001:DB8::1]') // Return true
Invalids mails :
validMail('Abc.example.com') // Return false
validMail('A@b@c@example.com') // Return false
validMail('a"b(c)d,e:f;g<h>i[j\k]l@example.com') // Return false
validMail('just"not"right@example.com') // Return false
validMail('this is"not\allowed@example.com') // Return false
validMail('this\ still\"not\\allowed@example.com') // Return false
validMail('john..doe@example.com') // Return false
validMail('john.doe@example..com') // Return false
Show this test : https://regex101.com/r/LHJ9gU/1
- 1,117
- 1
- 11
- 32
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.
- 4,368
- 3
- 34
- 65
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
}
Regex update 2018! 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
- 14
- 1
- 6
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
- 30,030
- 21
- 100
- 124
- 2,080
- 4
- 22
- 26
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])+
- 1,119
- 11
- 28
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
- 45,692
- 46
- 149
- 200
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.
- 8,121
- 6
- 51
- 67
I was looking for a Regex in JS that passes all Email Address test cases:
email@example.comValid emailfirstname.lastname@example.comEmail contains dot in the address fieldemail@subdomain.example.comEmail contains dot with subdomainfirstname+lastname@example.comPlus sign is considered valid characteremail@192.0.2.123Domain is valid IP addressemail@[192.0.2.123]Square bracket around IP address is considered valid“email”@example.comQuotes around email is considered valid1234567890@example.comDigits in address are validemail@domain-one.exampleDash in domain name is valid_______@example.comUnderscore in the address field is validemail@example.name.nameis valid Top Level Domain nameemail@example.co.jpDot in Top Level Domain name also considered valid (usingco.jpas example here)firstname-lastname@example.comDash in address field is valid
Here we go :
OR regex:
Regex = /(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@[*[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+]*/
- 9,491
- 15
- 33
- 49
- 2,222
- 16
- 22
Here's a list of several commonly used regular expressions valid in Android and Java:
User names:
"^[A-Za-z0-9_-]{min number of character,max number of character}$";Telephone numbers:
"(^\\+)?[0-9()-]*";Telephone numbers (optional):
^($|(^\\+)?[0-9()-]*)$";Email addresses:
"[a-zA-Z0-9_\\.\\+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-\\.]+";Email addresses (optional):
"^($|[a-zA-Z0-9_\\.\\+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-\\.]+)$";Web URL:
"^($|(http:\\/\\/|https:\\/\\/)?(www.)?([a-zA-Z0-9]+).[a-zA-Z0-9]*.[a-z]{3}.?([a-z]+)?)$";URL for YouTube shortener (youtu.be) URLs:
"https?\\:\\/\\/(www\\.)?youtu(\\.)?be(\\.com)?\\/.*(\\?v=|\\/v\\/)?[a-zA-Z0-9_\\-]+";Postal address:
"[a-zA-Z\\d\\s\\-\\,\\#\\.\\+]+";Non-empty fields:
"[^\\s]*";6-digit PIN:
"^([0-9]{6})?$";IFSC codes:
"^[^\\s]{4}\\d{7}$";SWIFT codes:
"^([0-9]{10})?$";
- 17,081
- 7
- 36
- 71
- 3,321
- 24
- 42
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 @.
- 29,897
- 7
- 30
- 53
- 2,088
- 17
- 30
In my case, I wanted to avoid ~ and # that's why I have used another solution:
function validEmail(email){
const regex = /^((?!\.)[\w\-_.]*[^.])(@\w+)(\.\w+(\.\w+)?[^.\W])$/;
return regex.test(email);
}
function validEmail(email){
const regex = /^((?!\.)[\w\-_.]*[^.])(@\w+)(\.\w+(\.\w+)?[^.\W])$/;
return regex.test(email);
}
const emails = [
'pio_pio@factory.com',
'~pio_pio@factory.com',
'pio_~pio@factory.com',
'pio_#pio@factory.com',
'pio_pio@#factory.com',
'pio_pio@factory.c#om',
'pio_pio@factory.c*om',
'pio^_pio@factory.com'
]
for(const email of emails){
document.write(email+' : '+validEmail(email)+'</br>');
}
- 7,932
- 12
- 85
- 157
- 1,762
- 17
- 16
-
This answer - and a few others in this thread - do not escape the hyphen. From what I can see (September 2021) this poses no problem in browsers - at least the Webkit variants. However, this might change. At the time of writing PHP7.3 fails to compile the regex without escaping the hyphen. Future proof your browser side code by escaping the hyphen `\-` rather than just `-`. – DroidOS Sep 29 '21 at 12:28
Most of the answers here are not linter friendly, it's a mess! Some of them are also outdated!
After a lot of time spending, I decided to use an external library named email-validator, install it easily by npm for example and import/require it in your own project:
https://www.npmjs.com/package/email-validator
//NodeJs
const validator = require("email-validator");
validator.validate("test@email.com"); // true
//TypeScript/JavaScript
import * as EmailValidator from 'email-validator';
EmailValidator.validate("test@email.com"); // true
- 29,897
- 7
- 30
- 53
- 1,554
- 2
- 24
- 29
-
It's not the answer to the question, but it helped me and saved my time. This email-validator package seem to help round about half a million other (downloads) per week. So worth to mention and deserves some upvotes. – Stefan Oct 20 '20 at 15:02
The regular expression provided by Microsoft within ASP.NET MVC is
/^[\w-]+(\.[\w-]+)*@([a-z0-9-]+(\.[a-z0-9-]+)*?\.[a-z]{2,6}|(\d{1,3}\.){3}\d{1,3})(:\d{4})?$/
Which I post here in case it's flawed - though it's always been perfect for my needs.
- 71,299
- 12
- 93
- 154
- 6,316
- 2
- 28
- 52
Sectrean's solution works great, but it was failing my linter. So I added some escapes:
function validateEmail(email){
var re = /^(([^<>()[]\\.,;:\s@\"]+(\.[^<>()[]\\.,;:\s@\"]+)*)|(\".+\"))@(([[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
- 30,030
- 21
- 100
- 124
- 1,374
- 16
- 22
-
validateEmail("e_mail@sth.com") and validateEmail("e.mail@sth.com") both return `false` value – Ikrom Oct 22 '13 at 10:04
I've mixed @mevius and @Boldewyn Code to Create this ultimate code for email verification using JavaScript.
function ValidateEmail(email){
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var input = document.createElement('input');
input.type = 'email';
input.value = email;
return typeof input.checkValidity == 'function' ? input.checkValidity() : re.test(email);
}
I have shared this code on my blog here.
- 1,193
- 13
- 5
-
This will fail if the field is empty. You could add a required attribute and trim the email address to solve the issue. – Etienne Martin Nov 24 '18 at 21:29
This is a JavaScript translation of the validation suggested by the official Rails guide used by thousands of websites:
/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
Relatively simple but tests against most common errors.
Tested on a dataset of thousands of emails and it had zero false negatives/positives.
Example usage:
const emailRegex = /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i;
emailRegex.test('email@example.com'); // true
// Multi-word domains
emailRegex.test('email@example.co.uk'); // true
emailRegex.test('email@mail.gmail.com'); // true
// Valid special characters
emailRegex.test('unusual+but+valid+email1900=/!#$%&\'*+-/=?^_`.{|}~@example.com') // true
// Trailing dots
emailRegex.test('email@example.co.uk.'); // false
// No domain
emailRegex.test('email@example'); // false
// Leading space
emailRegex.test(' email@example.com'); // false
// Trailing space
emailRegex.test('email@example.com '); // false
// Incorrect domains
emailRegex.test('email@example,com '); // false
// Other invalid emails
emailRegex.test('invalid.email.com') // false
emailRegex.test('invalid@email@domain.com') // false
emailRegex.test('email@example..com') // false
- 1,480
- 3
- 17
- 33
I prefer to keep it simple and keep my users happy. I also prefer code which is easy to understand. RegEx is not.
function isValidEmail(value) {
const atLocation = value.lastIndexOf("@");
const dotLocation = value.lastIndexOf(".");
return (
atLocation > 0 &&
dotLocation > atLocation + 1 &&
dotLocation < value.length - 1
);
};
- Get the location of the last "@" and the last "."
- Make sure the "@" is not the first char (there is something before it)
- Make sure the "." is after the "@" and that there is at least one char between them
- Make sure there is at least a single char after the "."
Will this allow invalid email addresses to pass? Sure, but I don't think you need much more for a good user experience that allows you to enable/disable a button, display an error message, etc. You only know for sure that an email address is valid when you attempt to send an email to that address.
- 3,155
- 1
- 29
- 39
-
This will fail for emails ending in a comment containing a @, for example " elldffs@mydomain.kjfdij (this is @ comment)" which is a valid email – David Mårtensson Feb 16 '21 at 18:42
Here is a function I use for front end email validation. (The Regular Expression came from parsley.js)
<!DOCTYPE html>
<html>
<head>
<title>Our Company</title>
<style>
.form-style {
color: #ccc;
}
</style>
</head>
<body>
<h1>Email Validation Form Example</h1>
<input type="text" name="email" id="emailInput" class="form-style">
<script>
function validateEmail(emailAddress) {
var regularExpression = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))){2,6}$/i;
return regularExpression.test(emailAddress);
}
function showEmailValidationState(event) {
if (validateEmail(event.target.value)) {
document.getElementById("emailInput").style.color = 'black';
}
}
document.getElementById("emailInput").addEventListener("keyup", showEmailValidationState);
</script>
</body>
</html>
- 3,925
- 5
- 32
- 54
The best practice is to either use HTML5 built-in email tag.
<input type="email" name="email">
or the common email syntax as recognizing @ and . from the string is given below.
^[a-zA-Z0-9_\-.]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-.]+$
Note that this would still produce invalid email that will still match the regex, its almost impossible to catch them all but this will improve the situation a little.
- 848
- 8
- 26
-
See earlier comment 32 this is good, but the problem with this is that it must be inside a form tag and submitted by a submit input, which not everyone has the luxury of doing. Also, you can't really style the error message. – @Jason Nov 12 '11 at 0:08 – aNewb Dec 03 '20 at 02:24
Following Regex validations:
- No spacial characters before @
- (-) and (.) should not be together after @ No special characters after @ 2 characters must before @ Email length should be less 128 characters
function validateEmail(email) {
var chrbeforAt = email.substr(0, email.indexOf('@'));
if (!($.trim(email).length > 127)) {
if (chrbeforAt.length >= 2) {
var re = /^(([^<>()[\]{}'^?\\.,!|//#%*-+=&;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
//var re = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
return re.test(email);
} else {
return false;
}
} else {
return false;
}
}
Use the regular expression:
/^[a-z][a-zA-Z0-9_.]*(\.[a-zA-Z][a-zA-Z0-9_.]*)?@[a-z][a-zA-Z-0-9]*\.[a-z]+(\.[a-z]+)?$/
Example:
function validateEmail(email) {
var re = /^[a-z][a-zA-Z0-9_.]*(\.[a-zA-Z][a-zA-Z0-9_.]*)?@[a-z][a-zA-Z-0-9]*\.[a-z]+(\.[a-z]+)?$/;
return re.test(email);
}
It should allow only @ , . , _
- 71,299
- 12
- 93
- 154
- 126
- 7
You can also try
var string = "hmharsh3@gmail.com"
var exp = /(\w(=?@)\w+\.{1}[a-zA-Z]{2,})/i
alert(exp.test(string))
- 185
- 2
- 10
You can use this regex (from w3resource (*not related to W3C)):
/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(emailValue)
If you use Node you can use this in the back-end as well as the front-end.
I don't know other back-end languages so I cannot evaluate for other use cases.
- 21,480
- 12
- 75
- 86
- 919
- 9
- 13
-
4This regex fails on 'user+addition@gmail.com' and on 'user@email.longdomain'. Do not use. – Xizam Mar 24 '20 at 11:15
-
user+addition is a valid email and longdomain is not necessarily invalid.. – Mattia Rasulo Jan 08 '21 at 15:30
-
Exactly, no regex will ever be able to fully verify the format of an email and even if it would, it cannot know domain specific rules, just check for an @ and be done with it or send a verification email. Anything else is just asking for trouble. – David Mårtensson Feb 16 '21 at 18:30
If you're using Closure you can use the built-in goog.format.EmailAddress type:
http://docs.closure-library.googlecode.com/git/class_goog_format_EmailAddress.html
For example:
goog.format.EmailAddress.isValidAddrSpec("blah@blah.com")
Note that by reading the source (linked above) you can see the comments state that IDN are not supported and that it only aims to cover most addresses:
// This is a fairly naive implementation, but it covers 99% of use cases.
// For more details, see http://en.wikipedia.org/wiki/Email_address#Syntax
// TODO(mariakhomenko): we should also be handling i18n domain names as per
// http://en.wikipedia.org/wiki/Internationalized_domain_name
- 3,291
- 3
- 39
- 42
- 11,478
- 4
- 43
- 67
<pre>
**The personal_info part contains the following ASCII characters.
1.Uppercase (A-Z) and lowercase (a-z) English letters.
2.Digits (0-9).
3.Characters ! # $ % & ' * + - / = ? ^ _ ` { | } ~
4.Character . ( period, dot or fullstop) provided that it is not the first or last character and it will not come one after the other.**
</pre>
*Example of valid email id*
<pre>
yoursite@ourearth.com
my.ownsite@ourearth.org
mysite@you.me.net
xxxx@gmail.com
xxxxxx@yahoo.com
</pre>
<pre>
xxxx.ourearth.com [@ is not present]
xxxx@.com.my [ tld (Top Level domain) can not start with dot "." ]
@you.me.net [ No character before @ ]
xxxx123@gmail.b [ ".b" is not a valid tld ]
xxxx@.org.org [ tld can not start with dot "." ]
.xxxx@mysite.org [ an email should not be start with "." ]
xxxxx()*@gmail.com [ here the regular expression only allows character, digit, underscore and dash ]
xxxx..1234@yahoo.com [double dots are not allowed
</pre>
**javascript mail code**
function ValidateEmail(inputText)
{
var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(inputText.value.match(mailformat))
{
document.form1.text1.focus();
return true;
}
else
{
alert("You have entered an invalid email address!");
document.form1.text1.focus();
return false;
}
}
- 2,577
- 1
- 18
- 35
the best one :D (RFC-friendly & no error "too complex") :
function isMail(mail)
{
pattuser = /^([A-Z0-9_%+\-!#$&'*\/=?^`{|}~]+\.?)*[A-Z0-9_%+\-!#$&'*\/=?^`{|}~]+$/i;
pattdomain = /^([A-Z0-9-]+\.?)*[A-Z0-9-]+(\.[A-Z]{2,9})+$/i;
tab = mail.split("@");
if (tab.length != 2)
return false;
return (pattuser.test(tab[0]) && pattdomain.test(tab[1]));
}
- 730
- 8
- 20
If you are using ng-pattern and material this does the job.
vm.validateEmail = '([a-zA-Z0-9_.]{1,})((@[a-zA-Z]{2,})[\\\.]([a-zA-Z]{2}|[a-zA-Z]{3}))';
- 888
- 10
- 16
Here is the recommended Regex pattern for HTML5 on MDN:
Browsers that support the email input type automatically provide validation to ensure that only text that matches the standard format for Internet e-mail addresses is entered into the input box. Browsers that implement the specification should be using an algorithm equivalent to the following regular expression:
/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}
[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email#Validation
- 17,680
- 9
- 99
- 106
-
Good. Have you ever tried other validation methods like PHP or API services? Like DeBounce [Email Validation](https://debounce.io) Tool. – Iman Mar 09 '19 at 12:44
If you get this error: Using regular expressions is security-sensitive.
Then here is what you are looking for. This solution is free from " Regular expression Denial of Service (ReDoS) "
Regex to validate emails without (ReDoS):
/^[a-z0-9](?!.*?[^\na-z0-9]{2})[^\s@]+@[^\s@]+\.[^\s@]+[a-z0-9]$/
Please let me know if this solution works for you. Thanks.
- 29,897
- 7
- 30
- 53
- 834
- 8
- 8
Following Regex validations:
- No spacial characters before @
- (-) and (.) should not be together after @
- No special characters after @ 2 characters must before @
Email length should be less 128 characters
function validateEmail(email) { var chrbeforAt = email.substr(0, email.indexOf('@')); if (!($.trim(email).length > 127)) { if (chrbeforAt.length >= 2) { var re = /^(([^<>()[\]{}'^?\\.,!|//#%*-+=&;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/; return re.test(email); } else { return false; } } else { return false; } }
- 24,762
- 8
- 55
- 78
- 8,830
- 4
- 62
- 44
Whoever is using @pvl solution and wants it to pass ESLint Prefer-template then here's a version where I used template literals instead of string concatenation.
validateEmail(email) {
let sQtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]';
let sDtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]';
let sAtom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+';
let sQuotedPair = '\\x5c[\\x00-\\x7f]';
let sDomainLiteral = `\\x5b(${sDtext}|${sQuotedPair})*\\x5d`;
let sQuotedString = `\\x22(${sQtext}|${sQuotedPair})*\\x22`;
let sDomainRef = sAtom;
let sSubDomain = `(${sDomainRef}|${sDomainLiteral})`;
let sWord = `(${sAtom}|${sQuotedString})`;
let sDomain = `${sSubDomain}(\\x2e${sSubDomain})*`;
let sLocalPart = `${sWord}(\\x2e${sWord})*`;
let sAddrSpec = `${sLocalPart}\\x40${sDomain}`; // complete RFC822 email address spec
let sValidEmail = `^${sAddrSpec}$`; // as whole string
let reValidEmail = new RegExp(sValidEmail);
return reValidEmail.test(email);
}
- 790
- 7
- 12
In nodeJS you can also use validator node module and simply use like that
Install the library with npm install validator
var validator = require('validator');
validator.isEmail('foo@bar.com'); //=> true
- 1,835
- 22
- 34
There are some complex RegEx written here, that also works.
I tested this one and it works too:
[a-zA-Z0-9._]+[@]+[a-zA-Z0-9]+[.]+[a-zA-Z]{2,6}
Please test this here : http://www.regextester.com/?fam=97334
Hope this helps.
- 2,895
- 2
- 13
- 23
How about creating a function which will test any string against emails' pattern using regular expression in JavaScript, as we know email addresses can be quite different in different regions, like in UK and Australia it usually ends up with .co.uk or .com.au, so I tried to cover those as well, also check if the string passed to the function, something like this:
var isEmail = function(str) {
return typeof str==='string' && /^[\w+\d+._]+\@[\w+\d+_+]+\.[\w+\d+._]{2,8}$/.test(str);
}
and check if it's email like below:
isEmail('alex@example.com'); //true
isEmail('alireza@test.co.uk'); //true
isEmail('peter.example@yahoo.com.au'); //true
isEmail('alex@example.com'); //true
isEmail('peter_123@news.com'); //true
isEmail('hello7___@ca.com.pt'); //true
isEmail('example@example.co'); //true
isEmail('hallo@example.coassjj#sswzazaaaa'); //false
isEmail('hallo2ww22@example....caaaao'); //false
- 93,149
- 25
- 259
- 162
-
What happens with `alireza@test.uk` or `phil.h\@\@cked+liked~it@haacked.com`? – Agi Hammerthief Feb 01 '18 at 21:03
ES6 sample
const validateEmail=(email)=> /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email);
- 5,808
- 38
- 33
Here's a simple regex that would just check for the basic format of an email e.g., X@Y.C:
\S+@\S+\.\S+
- 5,146
- 7
- 53
- 64
This question is more dificult to answer than seems at first sight.
There were loads of people around the world looking for "the regex to rule them all" but the truth is that there are tones of email providers.
What's the problem? Well, "a_z%@gmail.com cannot exists but it may exists an address like that through another provider "a__z@provider.com.
Why? According to the RFC: https://en.wikipedia.org/wiki/Email_address#RFC_specification.
I'll take an excerpt to facilitate the lecture:
The local-part of the email address may use any of these ASCII characters:
- uppercase and lowercase Latin letters A to Z and a to z;
- digits 0 to 9;
- special characters !#$%&'*+-/=?^_`{|}~;
- dot ., provided that it is not the first or last character unless quoted, and provided also that it does not appear consecutively unless quoted (e.g. John..Doe@example.com is not allowed but "John..Doe"@example.com is allowed);[6]
Note that some mail servers wildcard local parts, typically the characters following a plus and less often the characters following a minus, so fred+bah@domain and fred+foo@domain might end up in the same inbox as fred+@domain or even as fred@domain. This can be useful for tagging emails for sorting, see below, and for spam control. Braces { and } are also used in that fashion, although less often.
- space and "(),:;<>@[\] characters are allowed with restrictions (they are only allowed inside a quoted string, as described in the paragraph below, and in addition, a backslash or double-quote must be preceded by a backslash);
- comments are allowed with parentheses at either end of the local-part; e.g. john.smith(comment)@example.com and (comment)john.smith@example.com are both equivalent to john.smith@example.com.
So, i can own an email address like that:
A__z/J0hn.sm{it!}h_comment@example.com.co
If you try this address i bet it will fail in all or the major part of regex posted all across the net. But remember this address follows the RFC rules so it's fair valid.
Imagine my frustration at not being able to register anywhere checked with those regex!!
The only one who really can validate an email address is the provider of the email address.
How to deal with, so?
It doesn't matter if a user adds a non-valid e-mail in almost all cases. You can rely on HTML 5 input type="email" that is running near to RFC, little chance to fail. HTML5 input type="email" info: https://www.w3.org/TR/2012/WD-html-markup-20121011/input.email.html
For example, this is an RFC valid email:
"very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@strange.example.com
But the html5 validation will tell you that the text before @ must not contain " or () chars for example, which is actually incorrect.
Anyway, you should do this by accepting the email address and sending an email message to that email address, with a code/link the user must visit to confirm validity.
A good practice while doing this is the "enter your e-mail again" input to avoid user typing errors. If this is not enough for you, add a pre-submit modal-window with a title "is this your current e-mail?", then the mail entered by the user inside an h2 tag, you know, to show clearly which e-mail they entered, then a "yes, submit" button.
- 1,504
- 1
- 12
- 19
General email regex (RFC 5322 Official Standard): https://emailregex.com/
JavaScript:
/^(([^<>()\[\]\\.,;:\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,}))$/
- 30,030
- 21
- 100
- 124
- 203
- 3
- 10
Search for the @ sign in the input field.
- 59
- 3
- 18
-
This! This is the only valid check you can really do that doesn't complicate things needlessly. If you really want to know if the email is valid, send the user an email. – oligofren Sep 24 '19 at 09:35
I add my Regex - i solved for me more little issues like characters from other languages or capital letters
^[a-zA-Z0-9][a-zA-Z0-9-_\.]+@([a-zA-Z]|[a-zA-Z0-9]?[a-zA-Z0-9-]+[a-zA-Z0-9])\.[a-zA-Z0-9]{2,10}(?:\.[a-zA-Z]{2,10})?$
- 2,556
- 21
- 31
Use the browser/runtime to handle parsing the input by prepending a protocol and pass it to the URL API, trapping any errors and check the resulting username and hostname properties of the result. It will handle basically all transformations and possibilities (punycode of character sets, etc). This only establishes that the input is parsable, not that is valid--that is only possible through checking if the destination machine receives messages for that alias. This provides a close (imo reasonable) guess though, and can be expanded to be more specific and realistic if you're comfortable both maintaining it and also risking invalid rejections. (Note it doesn't attempt to address IPv4 or IPv6 addresses, simply the broad range of customer-facing scenarios using a domain.)
function validEmail(email=''){
var $0, url, isValid = false, emailPatternInput = /^[^@]{1,64}@[^@]{4,253}$/, emailPatternUrl = /^[^@]{1,64}@[a-z][a-z0-9\.-]{3,252}$/i;
email = email.trim();
try{
url = new URL('http://'+email);
$0 = `${url.username}@${url.hostname}`;
isValid = emailPatternInput.test( email );
if(!isValid) throw 'invalid email pattern on input:' + email;
isValid = emailPatternUrl.test( $0 );
if(!isValid) throw 'invalid email pattern on url:' + $0;
console.log(`email looks legit "${email}" checking url-parts: "${$0 === email ? '-SAME-':$0}"`);
}catch(err){
console.error(`probably not an email address: "${email}"`, err);
};
return isValid;
}
['user+this@はじめよう.みんな', 'stuff@things', 'user+that@host.com', 'Jean+François@anydomain.museum','هيا@יאללה', '试@例子.测试.مثال.آزمایشی', 'not@@really', 'no'].forEach(email=>console.log(validEmail(email), email));
This is the both the simplest and most generally permissive example I can come up with. Please edit it in cases where it can be made to be more accurate while maintain its simplicity and reasonable generally permissive validity.
Also see MDN URL docs URL, window.URL and Nodejs for URL APIs.
- 1,969
- 23
- 25
You may try RegExp
function isValidEmail( value ) {
return /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,5}$/.test( value );
}
console.log( isValidEmail("mymail@mydomain.com") )
- 658
- 9
- 20
-
1Please, have a look at these sites: [TLD list](https://www.iana.org/domains/root/db); [valid/invalid addresses](https://en.wikipedia.org/wiki/Email_address#Examples); [regex for RFC822 email address](http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html) – Toto Nov 26 '19 at 13:50
// Try this regular Expression by ES6 function
const emailValidate = (email) => {
const regexp= /^[\w.%+-]+@[\w.-]+\.[\w]{2,6}$/;
return regexp.test(email);
}
- 883
- 7
- 7
-
This is a good example of why people say don't use regex for this. Take just a single piece of this, the assertion that a top-level domain will be 6 letters or less. This rejects just under half of all valid TLDs -- there are currently over 650 TLDs that are more than 6 characters, you can see them all at https://data.iana.org/TLD/tlds-alpha-by-domain.txt – Jason Kohles May 05 '22 at 02:17
Found the perfect regular expression. It excludes double @, two "." in a row, languages other than English and extra characters at the beginning of the line (".", "-", "!", etc.)
const regexp = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (!this.value.match(regexp)) {
// on error, we get into the condition
this.classList.add('error');
}
// this - email input
- 21
- 4
If you are using AngularJS, just add type="email" to the input element:
In case there is no input element, it can be created dynamically:
var isEmail = $compile('<input ng-model="m" type="email">')($rootScope.$new()).
controller('ngModel').$validators["email"];
if (isEmail('email@gmail.com')) {
console.log('valid');
}
- 24,762
- 8
- 55
- 78
- 104,478
- 28
- 147
- 111
-
But *what is* this email parser function? Could you post it so that one can use it without angular? – Bergi Dec 15 '14 at 02:07
-
Yes, if you are going to post a black box answer please dig up the RegEx behind the email parser function and show us what it's using.. – Eric Bishard Aug 24 '15 at 02:09
I know its not regex but any way...
This is example with node and npm package email-existence this is ultimate checking if email exist and if its in the right form :)
This will ping the email if its responding if it got no response it will return false or else true.
function doesEmailExist(email) {
var emailExistence = require('email-existence');
return emailExistence.check(email,function (err,status) {
if (status) {
return status;
}
else {
throw new Error('Email does not exist');
}
});
}
If you want to use Jquery and want to have modern approach then use JQuery input mask with validation.
http://bseth99.github.io/projects/jquery-ui/5-jquery-masks.html
Demo on how simple jquery input mask is here: http://codepen.io/anon/pen/gpRyBp
Example of simple input mask for date forexample NOT full validation
<input id="date" type="text" placeholder="YYYY-MM-DD"/>
and the script:
$("#date").mask("9999-99-99",{placeholder:"YYYY-MM-DD"});
- 1,377
- 2
- 16
- 44
This regexp prevents duplicate domain names like abc@abc.com.com.com.com, it will allow only domain two time like abc@abc.co.in. It also does not allow statring from number like 123abc@abc.com
regexp: /^([a-zA-Z])+([a-zA-Z0-9_.+-])+\@(([a-zA-Z])+\.+?(com|co|in|org|net|edu|info|gov|vekomy))\.?(com|co|in|org|net|edu|info|gov)?$/,
All The Best !!!!!
- 107
- 1
- 8
-
Why would you want to use something like this? The email address standards specification suggests that email addresses may begin with digits, and may contain multiple period characters in both the domain and lcoal part. This answer seems to be something you've created for some entirely custom scenario, where you effectively discriminate against people for having email addresses which you don't like! To extend slightly, email addresses could also contain IP addresses, so this is potentially even more restrictive than described. – XtrmJosh Nov 03 '15 at 13:24
-
True !!!!!!But different people can have different requirement and That is why we write validations....isn't it????????? – Brijeshkumar Nov 04 '15 at 09:53
-
Well, not really. We use validation to confirm that input matches our expectations in order to avoid trying to use badly formatted data in certain ways. In this instance, OP is looking for code which can validate an email address, as it is intended to be. In your instance, you appear to be validating a string to be something which you want it to be. To put it simply, you are validating that a string matches something that you want it to match, which isn't an email address, while OP is looking validating that a string matches an email address. These are not the same things. – XtrmJosh Nov 05 '15 at 19:11
I'd like to add a short note about non-ASCII characters. Rnevius's (and co.) solution is brilliant, but it allows to add Cyrillic, Japanese, Emoticons and other unicode symbols which may be restricted by some servers.
The code below will print true though it contains UTF-8 character Ё.
console.log (/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test ('Ё@example.org'))
In my case all non-ASCII symbols are prohibited so I have modified the original expression to exclude all characters above U+007F:
/^(([^\u0080-\uffff<>()\[\]\\.,;:\s@"]+(\.[^\u0080-\uffff<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
Maybe this will help someone to prevent undesired behaviour.
- 51
- 5
-
Nah I think this is an unusual enough use case that it should be its own answer – jcollum Aug 13 '17 at 17:48
<input type="email" class="form-control" required="required" placeholder="Email Address" name="Email" id="Email" autocomplete="Email">
<button class="btn-1 shadow-0 full-width" type="button" id="register">Register account</button>
$("#register").click(function(){
var rea = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
var Email = $("#Email").val();
var x = rea.test(Email);
if (!x) {
alert('Type Your valid Email');
return false;
}
</script>
- 19
- 5
Here is a solution that works and includes validation/notification fuctionality in a form:
You can run it at this link
JAVASCRIPT
(function() {
'use strict';
window.addEventListener('load', function() {
var form = document.getElementById('needs-validation');
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
}
form.classList.add('was-validated');
event.preventDefault();
}, false);
}, false);
})();
HTML
<p class='title'>
<b>Email validation</b>
<hr size="30px;">
</p>
<br>
<form id="needs-validation" novalidate>
<p class='form_text'>Try it out!</p>
<div class="form-row">
<div class="col-12">
<input type="email" class="form-control" placeholder="Email Address" required>
<div class="invalid-feedback">
Please enter a valid email address.
</div>
</div>
<div class="row">
<div class="col-12">
<button type="submit"
class="btn btn-default btn-block">Sign up now
</button>
</div>
</div>
</form>
- 2,920
- 1
- 22
- 34
I wrote a JavaScript email validator which is fully compatile with PHP's filter_var($value, FILTER_VALIDATE_EMAIL) implementation.
https://github.com/mpyw/FILTER_VALIDATE_EMAIL.js
import validateEmail from 'filter-validate-email'
const value = '...'
const result = validateEmail(value)
is equivalent to:
<?php
$value = '...';
$result = (bool)filter_var($value, FILTER_VALIDATE_EMAIL, FILTER_FLAG_EMAIL_UNICODE);
- 5,331
- 4
- 29
- 35
You cold use https://github.com/chriso/validator.js and simply do:
var validator = require('validator');
validator.isEmail('foo@bar.com'); //=> true
Note that this can work on the client.
- 1,220
- 15
- 31
Here's how I do it. I'm using match() to check for the standard email pattern and I'm adding a class to the input text to notify the user accordingly. Hope that helps!
$(document).ready(function(){
$('#submit').on('click', function(){
var email = $('#email').val();
var pat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (email.match(pat)){
$('#email')
.addClass('input-valid');
return false;
} else {
$('#email')
.addClass('input-error')
.val('');
return false;
}
});
});
.input-error {
border: 1px solid red;
color: red;
}
.input-valid {
border: 1px solid green;
color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="text" id="email" placeholder="name@service.xx" class="">
<input type="submit" id="submit" value="Send"/>
</form>
- 2,933
- 2
- 24
- 30
-
Have you ever tried DeBounce [Email Validation](https://debounce.io)? I suggest taking a look at this. – Iman Mar 04 '19 at 16:48
If you want something a human can read and maintain, I would recommend Masala Parser (I'm one of the creators of it).
import {C,Streams} from '@masala/parser'
const illegalCharset = ' @\u00A0\n\t';
const extendedIllegalCharset = illegalCharset + '.';
// Assume 'nicolas@internal.masala.co.uk'
export function simpleEmail() {
return C.charNotIn(illegalCharset).rep() // 'nicolas'
.then(C.char('@'))
.then(subDns()) //'internal.masala.co.'
.then(C.charNotIn(extendedIllegalCharset).rep()) //'uk'
.eos(); // Must be end of the char stream
}
// x@internal.masala.co.uk => extract 'internal.masala.co.'
function subDns() {
return C.charNotIn(extendedIllegalCharset).rep().then(C.char('.')).rep()
}
function validateEmail(email:string) {
console.log(email + ': ' + (simpleEmail().parse(Streams.ofString(email)).isAccepted()));
}
validateEmail('nicolas@internal.masala.co.uk'); // True
validateEmail('nz@co.'); // False, trailing "."
If you want to accept the ultimate ugly email version, you can add in quotes in the first part:
function inQuote() {
return C.char('"')
.then(C.notChar('"').rep())
.then(C.char('"'))
}
function allEmail() {
return inQuote().or(C.charNotIn(illegalCharset))
.rep() // repeat (inQuote or anyCharacter)
.then(C.char('@'))
.then(subDns())
.then(C.charNotIn(extendedIllegalCharset).rep())
.eos() // Must be end of the character stream
// Create a structure
.map(function (characters) { return ({ email: characters.join('') }); });
}
'"nicolas""love-quotes"@masala.co.uk' is officially valid, but should it be in your system?
At least with Masala, you give yourself a chance to understand it. And so for the next year, colleague.
- 30,030
- 21
- 100
- 124
- 6,855
- 3
- 48
- 67
These will work with the top used emails(they match exactly the rules of each one).
Gmail
/^[a-z]((?!\.\.)([a-z\.])){4,28}[a-z0-9]@gmail.com$/i
Yahoo
/^[a-z]((?!\.\.)([\w\.])){3,30}[\w]@yahoo.com$/i
Outlook/Hotmail
/[a-z]((?!\.\.)([\w\.])){0,62}[\w]@(outlook.com|hotmail.com)$/i
- 420
- 5
- 15
-
Do you know that `\w` already includes `\d` and `_`? Please, have a look at these sites: [TLD list](https://www.iana.org/domains/root/db); [valid/invalid addresses](https://en.wikipedia.org/wiki/Email_address#Examples); [regex for RFC822 email address](http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html) – Toto Nov 18 '19 at 12:50
-
@Toto that's right, i don't know how i lost it there, i actually used this regex in my database handaling :\, thanks again. – Eboubaker Nov 21 '19 at 16:30
-
Gmail's domain is not `@google.com`, it's `@gmail.com` or (for very old accounts) `@googlemail.com` – David Wheatley Jan 21 '20 at 17:36
// Html form call function name at submit button
<form name="form1" action="#">
<input type='text' name='text1'/>
<input type="submit" name="submit" value="Submit"
onclick="ValidateEmail(document.form1.text1)"/>
</from>
// Write the function name ValidateEmail below
<script>
function ValidateEmail(inputText)
{
var mailformat = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
if(inputText.value.match(mailformat))
{
alert("Valid email address!");
document.form1.text1.focus();
return true;
}
else
{
alert("You have entered an invalid email address!");
document.form1.text1.focus();
return false;
}
}
</script>
- 457
- 5
- 11
Yet another perfect regexp for email validation
/^([^\s\@])+\@(([^\s\@\.])+\.)+([^\s\.]{2,})+$/
You can test it here https://regex101.com/r/FV3pUI/2
- 7,389
- 2
- 43
- 50
One of my coworker shared this regex with me. I like it a lot.
function isValidEmailAddress (email) {
var validEmail = false;
if (email) {
email = email.trim().toLowerCase();
var pattern = /^[\w-']+(\.[\w-']+)*@([a-zA-Z0-9]+[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*?\.[a-zA-Z]{2,6}|(\d{1,3}\.){3}\d{1,3})(:\d{4})?$/;
validEmail = pattern.exec(email);
}
return validEmail;
}
if (typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
};
}
- 583
- 6
- 20
\b[a-z][\w\d_\.]+@\w+\.[a-z]{2}[a-z]?\.?[a-z]{,2}\s
It allows:
abcxyz123@qwert.com
abc123xyz@asdf.co.in
abc1_xyz1@gmail1.com
abc.xyz@gmail.com.in
- 580
- 1
- 9
- 19
- 39
- 6
-
Nice try: 2 updates here: For match ranges, we provide `{min,max}`. A blank `min` is error, but can have a blank `max`. I mean `[a-z]{,2}` is wrong, write as `{0,2}`. Moreover: your regex shows `kamal@_gmail.com` as valid which is not! – Kamal Nayan Mar 14 '16 at 10:46
If you define your regular expression as a string then all backslashes need to be escaped, so instead of '\w' you should have '\w'.
Alternatively, define it as a regular expression:
var pattern = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
- 89
- 1
- 1
- 10
Now ReactNative Version 0.46 Use Below code for email Validation.
validateEmail = (email) => {
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (re.test(email)) {
} else {
alert('email: ' + "Please enter valid emailID.")
}
}
- 22,359
- 14
- 86
- 110
There is my version of an email validator. This code is done with object-oriented programming and realized as a class with static methods. You will find two versions of the validators: strict(EmailValidator.validate) and kind(EmailValidator.validateKind).
The first throws an error if an email is invalid and returns email otherwise. The second returns Boolean value that says if an email is valid. I prefer the strict version in most of the cases.
export class EmailValidator {
/**
* @param {string} email
* @return {string}
* @throws {Error}
*/
static validate(email) {
email = this.prepareEmail(email);
const isValid = this.validateKind(email);
if (isValid)
return email;
throw new Error(`Got invalid email: ${email}.`);
}
/**
* @param {string} email
* @return {boolean}
*/
static validateKind(email) {
email = this.prepareEmail(email);
const regex = this.getRegex();
return regex.test(email);
}
/**
* @return {RegExp}
* @private
*/
static getRegex() {
return /^(([^<>()\[\]\\.,;:\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,}))$/;
}
/**
* @param {string} email
* @return {string}
* @private
*/
static prepareEmail(email) {
return String(email).toLowerCase();
}
}
To validate an email you can follow these ways:
// First way.
try {
EmailValidator.validate('balovbohdan@gmail.com');
} catch (e) {
console.error(e.message);
}
// Second way.
const email = 'balovbohdan@gmail.com';
const isValid = EmailValidator.validateKind(email);
if (isValid)
console.log(`Email is valid: ${email}.`);
else
console.log(`Email is invalid: ${email}.`);
- 30,030
- 21
- 100
- 124
- 453
- 4
- 12
I am using this function
/**
* @param {*} email
*/
export const validateEmail = email => {
return new RegExp(/[\w-]+@([\w-]+\.)+[\w-]+/gm).test(email);
};
- 8,144
- 8
- 51
- 91
-
Doesn't work for Unicode. `validateEmail('køkø@gmail.com') === false`. Forget validation using checks like this. Test for `@` and just send the user an email. – oligofren Sep 24 '19 at 09:36
for email validation you can create your custom function and use regex syntax for validate email:
function validateEmail(email){
var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
//your custom code here to check your email address
}
- 608
- 3
- 9
-
1Please, have a look at these sites: [TLD list](https://www.iana.org/domains/root/db); [valid/invalid addresses](https://en.wikipedia.org/wiki/Email_address#Examples); [regex for RFC822 email address](http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html) – Toto Nov 18 '19 at 12:51
This works well for a simple email regex:
anythingExceptAtOrSpace@anythingExceptAtOrSpace.anythingExceptAtOrSpace
/^[^@ ]+@[^@ ]+\.[^@ ]+$/
To test:
const emailRegex = /^[^@ ]+@[^@ ]+\.[^@ ]+$/
const result1 = emailRegex.test('hello@there.com')
console.log(result1) // true
const result2 = emailRegex.test('hel@lo@there.com')
console.log(result2) // false
- 45,909
- 39
- 198
- 245
-
This doesn't match `me@localhost` (valid) but matches `...@...` (invalid). Please, have a look at these sites: [TLD list](https://www.iana.org/domains/root/db); [valid/invalid addresses](https://en.wikipedia.org/wiki/Email_address#Examples); [regex for RFC822 email address](http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html) – Toto Apr 18 '21 at 08:15
-
Yeah this isn't meant to be a catch all solution but rather a human readable regex that works for most cases - basically a simple regex to filter out most the rubbish – danday74 Apr 19 '21 at 00:35
Use the URL interface in JavaScript to parse the address in the minimum practical expected format user@host then check that it looks reasonable. Next send a message to it and see if that works (for example require the recipient validate a one-time token via the address). Note that this handles punycode, internationalization, as shown in the samples below.
https://developer.mozilla.org/en-US/docs/Web/API/URL
an example with simple tests:
function validEmail(input=''){
const emailPatternInput = /^[^@]{1,64}@[^@]{4,253}$/, emailPatternUrl = /^[^@]{1,64}@[a-z][a-z0-9\.-]{3,252}$/i;
let email, url, valid = false, error, same = false;
try{
email = input.trim();
// handles punycode, etc using browser's own maintained implementation
url = new URL('http://'+email);
let urlderived = `${url.username}@${url.hostname}`;
same = urlderived === email;
valid = emailPatternInput.test( email );
if(!valid) throw new Error('invalid email pattern on input:' + email);
valid = emailPatternUrl.test( urlderived );
if(!valid) throw new Error('invalid email pattern on url:' + urlderived);
}catch(err){
error = err;
};
return {email, url, same, valid, error};
}
[
'user+this@はじめよう.みんな'
, 'stuff@things.eu'
, 'stuff@things'
, 'user+that@host.com'
, 'Jean+François@anydomain.museum','هيا@יאללה'
, '试@例子.测试.مثال.آزمایشی'
, 'not@@really'
, 'no'
].forEach(email=>console.log(validEmail(email), email));
- 1,969
- 23
- 25
function ValidateEmail(mail)
{
if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(myForm.emailAddr.value))
{
return (true)
}
alert("You have entered an invalid email address!")
return (false)
}
Ref URL: https://www.w3resource.com/javascript/form/email-validation.php
- 44,696
- 30
- 102
- 125
- 2,501
- 2
- 16
- 33
This works for me:
function Email(mail)
{
if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(myForm.emailAddr.value))
{
return (true)
}
alert("Invalid email address!")
return (false)
}
- 25,730
- 12
- 57
- 71
- 41
- 4
A shorter answer to your question is: Validating" an e-mail address with a reg-ex is something that any internet based service provider should desist from. The possibilities of kinds of domain names and e-mail addresses have increased so much in terms of variety, any attempt at validation, which is not well thought may end up denying some valid users into your system.
However, there is one good library available in Javascript i.e. "validator.js". It is a popular javascript package for various validations and can be used to validate & normalize email before sending email. It has good compliance when it comes to being inclusive towards IDNs and Internationalized Email addresses.
The longer answer to this can be found below:
There are three RFCs that lay down the foundation for the "Internet Message Format"
- RFC 822
- RFC 2822 (Supercedes RFC 822)
- RFC 5322 (Supercedes RFC 2822)
The RFC 5322, however, defines the e-mail IDs and their naming structure in the most technical manner. That is more suitable laying down the foundation an Internet Standard that liberal enough to allow all the use-cases yet, conservative enough to bind it in some formalism.
However, the e-mail validation requirement from the software developer community, has the following needs -
- to stave off unwanted spammers
- to ensure the user does not make inadvertent mistake
- to ensure that the e-mail ID belongs to the actual person inputting it
They are not exactly interested in implementing a technically all-encompassing definition that allows all the forms (IP addresses, including port IDs and all) of e-mail id. The solution suitable for their use-case is expected to solely ensure that all the legitimate e-mail holders should be able to get through. The definition of ""legitimate"" differes vastly from techical stand-point (RFC 5322 way) to usability stand-point(this solution). The usability aspect of the validation aims to ensure that all the e-mail IDs validated by the validation mechanism belong to actual people, using them for their communication purposes. This, thus introduces another angle to the validation process, ensuring an actually ""in-use"" e-mail ID, a requirement for which RFC-5322 definition is clearly not sufficient.
Thus, on practical grounds, the actual requirements boil down to this -
- To ensure some very basic validation checks
- To ensure that the inputted e-mail is in use
Second requirement typically involves, sending a standard response seeking e-mail to the inputted e-mail ID and authenticating the user based on the action delineated in the response mechanism. This is the most widely used mechanism to ensure the second requirement of validating an ""in use"" e-mail ID. This does involve round-tripping from the back-end server implementation and is not a straight-forward single-screen implementaion, however, one cannot do away with this.
The first requirement, stems from the need that the developers do not want totally ""non e-mail like"" strings to pass as an e-mail. This typically involves blanks, strings without ""@"" sign or without a domain name. Given the punycode representations of the domain names, if one needs to enable domain validation, they need to engage in full-fledged implementation that ensures a valid domain name. Thus, given the basic nature of requirement in this regard, validating for ""@."" is the only apt way of satisfying the requirement.
A typical regex that can satisfy this requirement is: ^[^@\s]+@[^@\s.]+.[^@\s.]+$ The above regex, follows the standard Perl regular-expression standard, widely followed by majority of the programming languages. The validation statement is: <anything except whitespaces and ""@"" sign>@<anything except whitespaces and ""@"" sign>.<anything except whitespaces, @ sign and dot>
For those who want to go one step deeper into the more relevant implementations, they can follow the following validation methodology. @
For - Follow the guidelines by the ""Universal Acceptance Steering Group"" - UASG-026 - https://uasg.tech/download/uasg-028-considerations-for-naming-internationalized-email-mailboxes-en/ For , you can follow any domain validation methodology using standard libraries, depending on your programming language. For the recent studies on the subject, follow the document UASG-018A - https://uasg.tech/download/uasg-018a-ua-compliance-of-some-programming-language-libraries-and-frameworks-en/. In addition, those who are interested to know the overall process, challenges and issues one may come across while implementing the Internationalized Email Solution, they can also go through the following RFCs: RFC 6530 (Overview and Framework for Internationalized Email), RFC 6531 (SMTP Extension for Internationalized Email), RFC 6532 (Internationalized Email Headers), RFC 6533 (Internationalized Delivery Status and Disposition Notifications), RFC 6855 (IMAP Support for UTF-8), RFC 6856 (Post Office Protocol Version 3 (POP3) Support for UTF-8), RFC 6857 (Post-Delivery Message Downgrading for Internationalized Email Messages), RFC 6858 (Simplified POP and IMAP Downgrading for Internationalized Email)."
- 56
- 3
-
You have posted this as a new answer with updates a few times now. If you want to update it, you should click on the [edit] link rather than deleting it and posting a new answer. – Stephen Ostermiller May 04 '22 at 12:10
The personal_info part contains the following ASCII characters.
- Uppercase (A-Z) and lowercase (a-z) English letters. Digits (0-9).
- Characters ! # $ % & ' * + - / = ? ^ _ ` { | } ~
- Character . ( period, dot or fullstop) provided that it is not the first or last character and it will not come one after the other.
The domain name [for example com, org, net, in, us, info] part contains letters, digits, hyphens, and dots.
function ValidateEmail(mail)
{
if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(myForm.emailAddr.value))
{
return (true)
}
alert("You have entered an invalid email address!")
return (false)
}
- 99
- 2
- 10
You could also use RegExp:
function validateEmail(str) {
return new RegExp(/([\w\.\-_]+)?\w+@[\w-_]+(\.\w+){1,}/, 'igm').test(str);
}
See the Regular Expressions guide on MDN for more info.
- 21,480
- 12
- 75
- 86
- 881
- 1
- 8
- 19
-
1No this will not work for a lot of the active emails of the world and will accept emails that are not possible, do not use! – David Mårtensson Feb 16 '21 at 18:26
Simple suggestion, since i've seen confusion through the answers.
function validaEmail(email){
if(email.includes("@")){
if(email.split("@")[1].includes(".")){
return true;
}
}
return false;
}
- 41
- 3
-
honestly, I tried some of the regex based examples and they eventually failed on a valid email address, so I came up with a similar solution to Guilherme Santana . I won't post it for fear of being downvoted! But I would suggest for both the .includes in this solution you start at index 1, to exclude something like a@.b, or @b.c - I would also check that email.split("@")[1] doesn't include another @ symbol, and do an initial check for no whitespace on the whole string. – LairdPleng Feb 03 '22 at 02:36
Very simple in JavaScript. follow this code.
function validate(){
var email = document.getElementById('Email');
var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value))
{
alert('Please Enter the valid email address');
email.focus;
return false;
}
else
{
return true;
}
HTML code for this:
form name="form"
enctype="multipart/form-data"
name="form"
action="register.php"
method="POST" onsubmit="return validate();" >
<input type="text" placeholder="Enter ur Email Id" id="Email" name="Email" />
<input type="submit" id="submit" value="save" name="Like" class="button" />
</form>
- 2,876
- 3
- 23
- 28
-
2This filter invalidates many common valid e-mail addresses... For example: user+tag@gmail.com – kjpires Feb 28 '14 at 19:03
-
1Have a look at http://en.wikipedia.org/wiki/Email_address#Valid_email_addresses and http://data.iana.org/TLD/tlds-alpha-by-domain.txt – Toto Mar 07 '14 at 10:31
Simple regex for email-Id
String EMAIL_PATTERN ="^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$";
- 577
- 10
- 15
-
3According to your regex "_..............kamal@gmail.com" is valid, which should not be! – Kamal Nayan Mar 14 '16 at 10:38
function validatecontactEmail(email) {
if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email))
{
return (true)
}
return (false)
}
- 9
- 2
- 5
-
6How about just `return /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)`? – Michael Schilling Nov 14 '14 at 03:24
W3Schools gives a good simple and efficient script to validate an email:
function validateEmail(email) {
var atpos=email.indexOf("@");
var dotpos=email.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos+2 || dotpos+2 >= email.length) {
alert("Not a valid e-mail address");
return false;
}
return true;
}
Note that you will have to remove spaces if there are any though, with something like this:
.replace(/ /g,'')
Source: JavaScript Form Validation
- 30,030
- 21
- 100
- 124
- 1,298
- 12
- 22
Validation regex for email:
var rex_email = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if(email=="") {
window.plugins.toast.showShortBottom( "Please enter the details. ", function(a) {
console.log('toast success: ' + a);
}, function(b) { });
} else if(!rex_email.test(email)) {
window.plugins.toast.showShortBottom( "Please enter the valid email id. ", function(a) {
console.log('toast success: ' + a);
}, function(b) { });
}
- 40,889
- 58
- 100
- 149
- 719
- 10
- 8
-
2This will work for very common, basic email addresses, but there are certain edge cases where this will reject valid email addresses. If you've read the other 36(!) answers on here, you would have known that by now. – Qantas 94 Heavy Feb 07 '15 at 00:12
function validateEmail(elementValue){
var emailPattern = /^[a-zA-Z0-9._]+[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-zA-Z]{2,4}$/;
return emailPattern.test(elementValue);
}
It returns true if the email address is valid. Otherwise, it will return false.
- 30,030
- 21
- 100
- 124
- 114
- 3
Following regular expression:
/^([\w]+)(.[\w]+)*@([\w]+)(.[\w]{2,3}){1,2}$/;
- 21,611
- 14
- 96
- 136
- 6,807
- 8
- 49
- 59