How to validate an email address in JavaScript

Created 05.09.2008 16:10
Viewed 3.52M times
4845 votes

Is there a regular expression to validate an email address in JavaScript?

3
Comments
Warning!! The accepted answer if factually wrong as it does not conform to specifications. Read all answers for more details. by David Mårtensson, 16.02.2021 18:25
@DavidMårtensson It's mostly useless to validate emails according to the specification, the specification is much more liberal compared to what de facto is considered to be a well formed email. If your goal is for example to validate an email in a form to catch mistakes you can't conform to the specification, it's just too forgiving to catch actual user errors. by Alex, 19.03.2021 11:02
@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. by David Mårtensson, 03.05.2021 14:56
Answers 50
12
5610

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

function validateEmail(email) {
    const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(String(email).toLowerCase());
}

Here's the example of regular expresion 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:

function validateEmail(email) {
  const re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  return re.test(email);
}

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

$("#validate").on("click", validate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form>
  <p>Enter an email address:</p>
  <input id='email'>
  <button type='submit' id='validate'>Validate!</button>
</form>

<h2 id='result'></h2>

05.09.2008 16:15
Comments
This regex eliminates valid, in-use emails. Do not use. Google for "RFC822" or "RFC2822" to get a proper regex. by Randal Schwartz, 08.09.2010 02:34
This 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. by Vroo, 26.10.2012 06:32
You 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. by Kevin Fegan, 01.02.2014 08:49
These days Javascript can be run on a server so for those thinking this is only relevant for client side validation you are wrong. And to those who say its not possible to validate an email I believe your missing the point of validation in general. YOU WILL NEVER write validation for a form to ensure that everything is 100% perfect for two main reasons: 1. It would take more time than it would be worth to write the logic and 2. There will always be an edge case where bad data could get submitted. The reason we validate is to encourage proper data submission and prevent mistakes. by Cleanshooter, 08.04.2015 15:02
Watch out, this is invalid: re.test("username+something@gmail.com") by adriaan, 18.05.2015 13:47
That answer does not accept a gmail valid email like "foo+bar@gmail.com" by Felipe Skinner, 06.11.2015 15:24
Perhaps it should be.phrased "... validate email format .." per Kevin's comment. Also now with HTML5 there is.the type="email". by brw, 30.08.2020 21:51
This regex is not secure and potential for ReDoS. check: stackblitz.com/edit/js-nllx8y by Mar, 28.09.2020 07:54
How can I put this as a pattern on my input instead? by Ryan H, 07.10.2020 15:49
All this JS and RegEx without even checking for valid lengths (64 octets max + @ + 255 octets max) as per RFC 3696 §3. by AmigoJack, 15.10.2020 22:38
This answer if factually wrong and should not be accepted! by David Mårtensson, 16.02.2021 18:24
when something so simple and easy to understand exists (like below answer) why use such a long hard to understand in one go regex!? by krupesh Anadkat, 02.04.2021 06:10
Show remaining 7 comments
6
1008

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@]+$/

Example JavaScript function:

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

09.02.2012 02:22
Comments
You 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! by user83358, 30.07.2012 18:20
@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') by OregonTrail, 09.08.2012 14:58
@OregonTrail Valid email addresses can contain @ characters within quotes, and your regex would reject them. Arguably that puts it in an undesirable middle ground where it has both type I and type II errors (i.e. you'd be better off with just type I errors from the large regex, or just type II errors from the tiny one). Admittedly it's a trade-off, since a double-@ typo is pretty easy to do and emails containing extra @'s are pretty much non-existent in practice. by Paul Hendry, 03.12.2020 19:13
Worked pretty nice for me until one son of a client entered "something@gmail.com This is my 📧" - turned out it also allows emojis and whitespaces :/ So my recommendation is at least check for the string start and end by adding ^ and $ - /^\S+@\S+\.\S+$/ by scythargon, 08.03.2021 14:46
I tried to implement in my code but inside <script> tags @ symbol not accepted in string regex variable. How I can Solve this? by hkyaaa, 31.03.2021 06:58
The "prevent matching multiple @" version has one other regression: > /^[^\s@]+@[^\s@]+$/.test('foo@bar') > true by Wayne Ye, 06.05.2021 22:10
Show remaining 1 comments
3
824

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'tread on) implement it with this regular expression:

(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])

(...) We get a more practical implementation of RFC 2822 if we omit the syntax using double quotes and square brackets. It will still match 99.99% of all email addresses in actual use today.

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

A further change you could make is to allow any two-letter country code top level domain, and only specific generic top level domains. This regex filters dummy email addresses like asdf@adsf.adsf. You will need to update it as new top-level domains are added.

[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum)\b

So even when following official standards, there are still trade-offs to be made. Don't blindly copy regular expressions from online libraries or discussion forums. Always test them on your own data and with your own applications.

Emphasis mine

03.09.2009 14:26
Comments
NB: "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 ;)) by Piskvor left the building, 13.06.2012 15:51
there are now so many top level domains that filtering on them is counter productive. or at least prone to constant change. by pstanton, 23.07.2020 23:35
This doesn't seem to cover comments in email addresses, which are in the RFC, however absurd the notion. matt@example (this is comment don't you know) .com should be matched, but is not. by Matt Ellen, 08.02.2021 16:41
6
422

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.

07.09.2008 21:21
Comments
+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. by kommradHomer, 19.07.2012 07:14
You can still keep it simple but do a little more to ensure it has a "." somewhere after the @ followed by only numbers or digits, so things like me@here, me@here@, and me@herecom aren't valid... ^\S+@\S+[\.][0-9a-z]+$ by Tim Franklin, 21.03.2013 04:06
I think e-mail addresses can contain spaces. It's probably better to use .+@.+ by Sam, 10.04.2013 23:51
/\S+@\S+/.test("áéíóúý@ÁÉÍÓÚÝð") true by gtournie, 27.01.2014 04:57
@gtournie Nobody cares. Nobody is going to enter that into an email field by accident, and that is all front-end validation is for: To prevent people from accidentally entering the wrong bit of information, such as their name, in an email field. by meagar, 31.01.2015 14:59
It depends. Like - whenever you integrate with any third party, you better make sure your email is valid otherwise you will hate the mistake you just made. Make sure you understand the problem you're trying to solve well enough. Yes the above answers seem overly verbose, but they cover a lot of ground for good reason. by Julian Krispel-Samsel, 13.11.2020 16:03
Show remaining 1 comments
3
345

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.

02.05.2009 17:18
Comments
-1 why would i want to spend my time validating an email address that doesn't even pass the regex control ? by kommradHomer, 19.07.2012 07:16
@PaoloBergantino i mean that , why would i try to send a mail to check an obviously wrong mail address? even if i need to "be absolutely, positively sure that what the user entered is in fact an email" , i would only check the email addresses that match the regex by kommradHomer, 19.07.2012 14:32
@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. by Stephen P, 07.03.2013 01:40
3
238

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 production of the following ABNF, the character set for which is Unicode.

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

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

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

/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/
17.10.2011 08:23
Comments
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. by Jason, 12.11.2011 00:08
Dec 2020 @Jason - Does using the HTML5 validation still require 'inside a form tag and submitted by a submit input'? or can it be 'called' in Javascript. This validation seems to happen AFTER my coded Javascript validations. by aNewb, 03.12.2020 02:13
HTML semantic require to have a <form /> element if you are displaying form component. That being said, you should always use a form when using input. by Dimitri Kopriwa, 23.12.2020 17:44
1
158

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.

21.09.2015 01:52
Comments
It fits what you defined yourself, but the host part of an e-mail address is not necessarily a domain. Hence, a dot is not something you can rely on - examples: john@[::1] and john@server. by AmigoJack, 15.10.2020 22:26
2
100

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.

20.12.2012 15:20
Comments
This is a clever idea to punt on the problem but it doesn't work because browsers have crappy validation as well. E.g. .@a validates as true in current versions of Chrome, Firefox, and Safari. by Hank, 02.05.2013 18:44
@HenryJackson Unfortunately, in this case yes. This is because according to the RFC that is a valid e-mail address (think intranets). Browsers would get grilled, if they validate too narrow and produce false negatives. by Boldewyn, 03.05.2013 07:02
5
66

All email addresses contain an 'at' (i.e. @) symbol. Test that necessary condition:

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.

14.07.2013 18:15
Comments
what if there will be more than one '@' symbol? other restricted symbols? This validation cannot be trusted... by iwazovsky, 26.04.2015 10:14
is a@b valid email ? by Aravin, 20.12.2020 10:17
@Aravin It could be, on a LAN. by Nayuki, 21.12.2020 05:56
but it question is generic, not for local sytem of LAN by Aravin, 21.12.2020 09:47
Its 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 by David Mårtensson, 16.02.2021 18:37
2
70

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)>)$
05.09.2008 16:13
Comments
@Kato: It uses some incompatible extensions, including (?> to stop backtracking and (?<angle><)…(?(angle)>) to avoid providing a lengthy |. by Ry-, 09.03.2014 20:05
The match method returns an array, the test method, which returns a boolean, would be better for this situation. by iPzard, 07.11.2020 20:43
2
71

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);
}
15.04.2013 13:31
Comments
IDN addresses are not validated (info@üpöü.com) by D.A.H, 17.08.2014 17:38
'a@a' returns valid: jsfiddle.net/pmiranda/guoyh4dv by pmiranda, 02.02.2021 18:18
1
68

Correct validation of email address in compliance with the RFCs is not something that can be achieved with a one-liner regular expression. An article with the best solution I've found in PHP is What is a valid email address?. Obviously, it has been ported to Java.I think the function is too complex to be ported and used in JavaScript.JavaScript/node.js port: https://www.npmjs.com/package/email-addresses.

A good practice is to validate your data on the client, but double-check the validation on the server. With this in mind, you can simply check whether a string looks like a valid email address on the client and perform the strict check on the server.

Here's the JavaScript function I use to check if a string looks like a valid mail address:

function looksLikeMail(str) {
    var lastAtPos = str.lastIndexOf('@');
    var lastDotPos = str.lastIndexOf('.');
    return (lastAtPos < lastDotPos && lastAtPos > 0 && str.indexOf('@@') == -1 && lastDotPos > 2 && (str.length - lastDotPos) > 2);
}

Explanation:

  • lastAtPos < lastDotPos: Last @ should be before last . since @ cannot be part of server name (as far as I know).

  • lastAtPos > 0: There should be something (the email username) before the last @.

  • str.indexOf('@@') == -1: There should be no @@ in the address. Even if @ appears as the last character in email username, it has to be quoted so " would be between that @ and the last @ in the address.

  • lastDotPos > 2: There should be at least three characters before the last dot, for example a@b.com.

  • (str.length - lastDotPos) > 2: There should be enough characters after the last dot to form a two-character domain. I'm not sure if the brackets are necessary.

02.03.2011 11:26
Comments
i think this is a better take on validation of email compared to regex, regex is great, but may be not a right tool for this problem. only suggestion would be to have this chain of validation rules broken out into descriptive variables, just for readability sake of this example by GnrlBzik, 09.12.2020 02:24
1
56

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;}
02.05.2009 17:19
Comments
At least the + sign, which is widely used, is missing in the user part. by jofel, 27.04.2021 15:39
4
48

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])?

Why? It's based on RFC 2822, which is a standard ALL email addresses MUST adhere to. And I'm not sure why you'd bother with something "simpler"... you're gonna copy and paste it anyway ;)

Often when storing email addresses in the database I make them lowercase and, in practice, regexs can usually be marked case insensitive. In those cases this is slightly shorter:

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

Here's an example of it being used in JavaScript (with the case insensitive flag i at the end).

var emailCheck=/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i;
console.log( emailCheck.test('some.body@domain.co.uk') );

Note:
Technically some emails can include quotes in the section before the @ symbol with escape characters inside the quotes (so your email user can be obnoxious and contain stuff like @ and "..." as long as it's written in quotes). NOBODY DOES THIS EVER! It's obsolete. But, it IS included in the true RFC 2822 standard, and omitted here.

Note 2: The beginning of an email (before the @ sign) can be case sensitive (via the spec). However, anyone with a case sensitive email is probably used to having issues, and, in practice, case insensitive is a safe assumption. More info: Are email addresses case sensitive?

More info: http://www.regular-expressions.info/email.html

01.11.2012 14:06
Comments
“make them in lowercase”? That’s a violation, most notably with the local part of the email. by John Greene, 20.03.2021 18:26
@JohnGreene good point, didn't know that was in the spec – that said, have yet to find a email provider that is case sensitive by Ryan Taylor, 08.04.2021 16:16
the local-part MUST be interpreted and assigned semantics only by the host specified in the domain part of the address. RFC5321 by John Greene, 08.04.2021 18:08
yes i understand what you're saying, and i'm glad you brought it up but i think anyone with a case-sensitive email address (especially that isn't all lowercase) is very used to having issues. but all for respecting the spec, and that's what this post is about so i'll add a caveat by Ryan Taylor, 09.04.2021 19:53
1
42

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

  • Original
    /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/

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

to pass the examples in Wikipedia Email Address.

And you can see the result in here.

enter image description here

01.07.2016 04:43
Comments
The local part has a maximum length, which is not validated. by AmigoJack, 15.10.2020 22:29
1
26

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...

19.12.2011 18:39
Comments
This allows the entry of so many invalid email addresses it is useless advice. by cazlab, 06.01.2012 23:07
1
24

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.

25.06.2013 06:30
Comments
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 by aNewb, 03.12.2020 02:19
0
19

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.

02.05.2009 17:23
0
18

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])\]))$/
11.09.2013 02:21
0
14

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

06.02.2018 20:42
0
12

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
28.05.2010 22:05
0
13

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])+
22.12.2016 07:44
0
15

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.

28.12.2016 02:51
0
14

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
}
29.11.2013 12:26
0
12

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.

01.10.2010 09:37
0
13

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'); }
05.06.2012 23:41
0
12

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
15.04.2013 11:53
1
10
<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>

<script language="JavaScript1.2">
    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)
    }
</script>

<script>
    function checkbae(){
        if (document.layers || document.getElementById || document.all)
            return checkemail()
        else
            return true
    }
</script>
31.01.2013 09:39
Comments
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 by aNewb, 03.12.2020 02:21
0
10

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

  • email@example.com Valid email

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

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

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

  • email@192.0.2.123 Domain is valid IP address

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

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

  • 1234567890@example.com Digits in address are valid

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

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

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

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

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

Here we go :

http://regexr.com/3f07j

OR regex:

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

Wikipedia standard mail syntax :

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

function validMail(mail)
{
    return /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()\.,;\s@\"]+\.{0,1})+([^<>()\.,;:\s@\"]{2,}|[\d\.]+))$/.test(mail);
}

// VALID MAILS

validMail('Abc@example.com') // Return true
validMail('Abc@example.com.') // Return true
validMail('Abc@10.42.0.1') // Return true
validMail('user@localserver') // Return true
validMail('Abc.123@example.com') // Return true
validMail('user+mailbox/department=shipping@example.com') // Return true
validMail('"very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@strange.example.com') // Return true
validMail('!#$%&\'*+-/=?^_`.{|}~@example.com') // Return true
validMail('"()<>[]:,;@\\\"!#$%&\'-/=?^_`{}| ~.a"@example.org') // Return true
validMail('"Abc@def"@example.com') // Return true
validMail('"Fred Bloggs"@example.com') // Return true
validMail('"Joe.\\Blow"@example.com') // Return true
validMail('Loïc.Accentué@voilà.fr') // Return true
validMail('" "@example.org') // Return true
validMail('user@[IPv6:2001:DB8::1]') // Return true

// INVALID MAILS

validMail('Abc.example.com') // Return false
validMail('A@b@c@example.com') // Return false
validMail('a"b(c)d,e:f;g<h>i[j\k]l@example.com') // Return false
validMail('just"not"right@example.com') // Return false
validMail('this is"not\allowed@example.com') // Return false
validMail('this\ still\"not\\allowed@example.com') // Return false
validMail('john..doe@example.com') // Return false
validMail('john.doe@example..com') // Return false

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

21.06.2017 09:10
Comments
(^[a-zA-Z0-9.!#$%&'*+=?^_`{|}~-]{0,64})+@[a-zA-Z0-9](?:[a-zA‌​-Z0-9-]{0,61}[a-zA-Z‌​0-9])?(?:\.[a-zA-Z0-‌​9](?:[a-zA-Z0-9-]{0,‌​61}[a-zA-Z0-9])?)*$ by Amol Aher, 01.04.2021 08:09
0
8

How to write Particular Regular Expression in android or java.

1) USER_NAME = "^[A-Za-z0-9_-]{min number of character,max number of character}$";

2) TELEPHONE = "(^\\+)?[0-9()-]*";

3) TELEPHONE_OPTIONAL = "^($|(^\\+)?[0-9()-]*)$";

4) EMAIL = "[a-zA-Z0-9_\\.\\+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-\\.]+";

5) EMAIL_OPTIONAL = "^($|[a-zA-Z0-9_\\.\\+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-\\.]+)$";

6) WEB_URL = "^($|(http:\\/\\/|https:\\/\\/)?(www.)?([a-zA-Z0-9]+).[a-zA-Z0-9]*.[a-z]{3}.?([a-z]+)?)$";

7) WEB_URL_YOUTUBE_BE = "https?\\:\\/\\/(www\\.)?youtu(\\.)?be(\\.com)?\\/.*(\\?v=|\\/v\\/)?[a-zA-Z0-9_\\-]+";

8) POSTAL_ADDRESS = "[a-zA-Z\\d\\s\\-\\,\\#\\.\\+]+";

9) FIELD_NOT_EMPTY = "[^\\s]*";

10) PINCODE = "^([0-9]{6})?$";

11) IFSC_CODE = "^[^\\s]{4}\\d{7}$";

12) SWIFT_CODE = "^([0-9]{10})?$";

13) PINCODE = "^([0-9]{6})?$";

12.06.2018 12:03
1
8

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.

04.12.2013 10:44
Comments
Doesn't allow +'s in the name part of the email. by Paul Go, 09.03.2015 15:19
0
6

Wow there are a lot of answers that contain slightly different regular expressions. I've tried some 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 @.

26.01.2020 19:36
1
6

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.

03.02.2020 15:38
Comments
This will fail for emails ending in a comment containing a @, for example " elldffs@mydomain.kjfdij (this is @ comment)" which is a valid email by David Mårtensson, 16.02.2021 18:42
0
6

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
21.06.2018 12:13
1
6

Sectrean's solution works great, but it was failing my linter. So I added some escapes:

function validateEmail(email){ 
     var re = /^(([^<>()[]\\.,;:\s@\"]+(\.[^<>()[]\\.,;:\s@\"]+)*)|(\".+\"))@(([[0-9]{1,3}\‌​.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; 
     return re.test(email); 
}
30.08.2012 15:00
Comments
validateEmail("e_mail@sth.com") and validateEmail("e.mail@sth.com") both return false value by Ikrom, 22.10.2013 10:04
0
5

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>
04.08.2014 18:33
1
6

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.

27.06.2016 23:36
Comments
This will fail if the field is empty. You could add a required attribute and trim the email address to solve the issue. by Etienne Martin, 24.11.2018 21:29
2
6

Most of the answers here are not linter friendly, it's a mess! Some of them are also out-dated! 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
07.07.2020 14:55
Comments
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. by Stefan, 20.10.2020 15:02
Saved me a bunch of time too. by jfriend00, 13.11.2020 23:00
1
5

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.

06.09.2015 06:31
Comments
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 by aNewb, 03.12.2020 02:24
0
4

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 @ , . , _

31.05.2016 08:30
0
4

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;
}
}
02.03.2015 07:19
0
4

You can also try

var string = "hmharsh3@gmail.com"
var exp = /(\w(=?@)\w+\.{1}[a-zA-Z]{2,})/i
alert(exp.test(string))
22.07.2017 03:33
2
-3

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>
26.02.2014 10:49
Comments
This filter invalidates many common valid e-mail addresses... For example: user+tag@gmail.com by kjpires, 28.02.2014 19:03
0
3
<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;
    }
    }
28.01.2014 05:40
4
4

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.

24.01.2020 17:32
Comments
This regex fails on 'user+addition@gmail.com' and on 'user@email.longdomain'. Do not use. by Xizam, 24.03.2020 11:15
user+addition is a valid email and longdomain is not necessarily invalid.. by Mattia Rasulo, 08.01.2021 15:30
........exactly by Xizam, 08.01.2021 16:05
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. by David Mårtensson, 16.02.2021 18:30
1
3

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

11.01.2019 20:04
Comments
Good. Have you ever tried other validation methods like PHP or API services? Like DeBounce Email Validation Tool. by Iman Hejazi, 09.03.2019 12:44
1
2

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.

06.04.2017 04:27
Comments
me@localhost fails. by Agi Hammerthief, 01.02.2018 21:08
1
2

Search for the @ sign in the input field.

27.05.2019 09:54
Comments
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. by oligofren, 24.09.2019 09:35
1
2

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") )

26.11.2019 10:09
Comments
Please, have a look at these sites: TLD list; valid/invalid addresses; regex for RFC822 email address by Toto, 26.11.2019 13:50