By pix0r

2008-09-05 16:10:11 8 Comments

How can an email address be validated in JavaScript?


@Antonio 2019-04-25 14:46:18

General Email Regex (RFC 5322 Official Standard):


/^(([^<>()\[\]\\.,;:\[email protected]"]+(\.[^<>()\[\]\\.,;:\[email protected]"]+)*)|(".+"))@((\[[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,}))$/

@Raheel Khan 2019-04-23 08:43:49

I am using this function

 * @param {*} email
export const validateEmail = email => {
    return new RegExp(/[\w-][email protected]([\w-]+\.)+[\w-]+/gm).test(email);

@sectrean 2008-09-05 16:15:34

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

function validateEmail(email) {
    var re = /^(([^<>()\[\]\\.,;:\[email protected]"]+(\.[^<>()\[\]\\.,;:\[email protected]"]+)*)|(".+"))@((\[[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:

var re = /^(([^<>()\[\]\.,;:\[email protected]\"]+(\.[^<>()\[\]\.,;:\[email protected]\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\[email protected]\"]+\.)+[^<>()[\]\.,;:\[email protected]\"]{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) {
  var re = /^(([^<>()[\]\\.,;:\[email protected]\"]+(\.[^<>()[\]\\.,;:\[email protected]\"]+)*)|(\".+\"))@((\[[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() {
  var $result = $("#result");
  var email = $("#email").val();

  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=""></script>

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

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

@Jon 2010-07-07 17:18:18

Could someone explain what this will and won't match against? (Given some of the additional answers below.) It would be nice to know a bit more information in order to determine which 'solution' to use for a project.

@Umber Ferrule 2010-07-19 09:48:27

+1: Only thing this won't let through are IPs instead of domains. It does accept domains starting or ending with a dash, and domains in excess of 64 chars in length, but other than this does a good enough job. Cheers.

@Randal Schwartz 2010-09-08 02:34:23

This regex eliminates valid, in-use emails. Do not use. Google for "RFC822" or "RFC2822" to get a proper regex.

@rossipedia 2010-09-14 18:08:40

@Randall: Can you give an example of an email address that this won't let through?

@evanmcd 2011-02-12 19:01:45

This works well for me, though I do get a complier error (unescaped '[') when using it with Appcelerator. Doesn't seem to cause a problem with the validation at all, however.

@Piskvor 2011-06-06 01:20:04

Note that any IDNs will have to be punycoded before this regex accepts them; any valid top-level IDNs will be rejected even in punycode form (as the xn- prefix won't match [a-zA-Z]).

@Nik Sumeiko 2011-09-30 08:45:32

Why on var re = ... line JSLint says: Unescaped ']', unescaped '[', spaces are hard to count, use {2}?

@Chris J 2012-04-04 07:56:18

There's a full test case of email addresses at ... (see for more details).

@Dan Osipov 2012-06-14 18:26:58

There is a section on RFC2822 validation on the bottom of this page:

@P.M 2012-09-13 20:02:47 passes :-)

@Vroo 2012-10-26 06:32:11

This doesn't even accept the examples in RFC 822. Some simple cases it doesn't match a\@[email protected], a(b) See the RFC for more. Here's a regex that won't reject any valid addresses [^@][email protected][^@]+\.[^@]+ and protects against common errors.

@Good Person 2012-12-21 22:22:57

@BenRoberts [email protected] - valid email address, in use, it fails

@Ben Roberts 2013-01-13 07:38:43

@GoodPerson I just tried to email [email protected] to tell him/her they have a cool email address. But alas, gmail wouldn't let me. I suspect whoever that is has bigger problems communicating with others via email than just my site's javascript validation! But thanks for rising to the challenge.

@Jobert Enamno 2013-01-14 09:43:25

I am wondering why when I entered it accepted the email? Meaning '#' is allowed?

@oligofren 2013-04-16 15:20:31

This is a solution that seems good with most native English speakers, but it fails the Turkey test (see Joel Spolsky). Most unicode letters are allowed, and for instance in Argentina, addresses such as "ñoñó[email protected]" is perfectly normal.

@Balwant Kumar Singh 2013-04-29 10:52:00

underscore(_) should be validated at first place I guess.

@user891193 2013-06-05 02:02:54

will fail for this kind of format:[email protected]

@Celeritas 2013-06-26 23:45:37

Examples of valid e-mail addresses that are marked as invalid are [email protected] and [email protected][IPv6:2001:db8:1ff::a0b:dbd0] see

@Alban 2013-07-23 15:05:27

@Alex 2013-10-21 12:24:54

@Ben it's the generic built in method in a regular expression.…

@jackocnr 2013-10-29 21:26:31

This passes for ı@a.aa (that first char is a weird one), which recently messed up our system.

@flying sheep 2013-11-04 11:20:30

@rossipedia example valid mail addresses that it doesn’t parse? e.g.: !#$%&'*+-/=?^_`{}|[email protected], or [email protected], or " " taken from wikipedia

@Wayne Burkett 2013-11-22 16:32:59

For all the people commenting that this is "good enough": look, you're simply thinking about this problem wrong. That's OK. It's a choice you can make for your users. I ain't mad at it. But, you know, technically speaking, you're demonstratively, provably wrong.

@niksmac 2014-01-29 04:26:06

its broke for [email protected] :(

@Kevin Fegan 2014-02-01 08:49:15

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: %[email protected], "%2", "a..b", "a_b", [email protected], [email protected] , [email protected] are all valid, but Gmail will never allow any of these email addresses. You should do this by accepting the email address and sending an email message to that email address, with a code/link the user must visit to confirm validity.

@PeeHaa 2014-02-05 12:37:38

For more info about what it (in)correctly matches see the following list

@josaphatv 2014-03-13 13:38:38

@BenRoberts [email protected] doesn't exist. And yet the regex will let it through.

@Justin 2014-05-28 18:21:35

According to wikipedia, unicode can exist in the domain name as well. var re = ...|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; should be var re = ...|(([^<>()[\]\\.,;:\[email protected]\"]+\.)+[a-zA-Z]{2,}))$/;

@Caqu 2014-09-03 20:19:18

This validates: "[email protected]"

@Synchro 2014-11-20 21:05:46

There are factors other than RFC822 in determining what an email address may be - for example [email protected] is valid RFC822, but 'dotless' domains are banned by ICANN, so it should be considered invalid.

@etoxin 2015-01-14 00:25:12

If you need to use this with the HTML5 Pattern API instead of using type="email" you will need to encode the quotation marks like so eg. <input pattern="^(([^<>()[\]\\.,;:\[email protected]\&quot;]+(\.[^<>()[\]\\.,;:\[email protected]‌​\&quot;]+)*)|(\&quot‌​;.+\&quot;))@((\[[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,})‌​)$" id="email" name="email" type="text">

@Cleanshooter 2015-04-08 15:02:14

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.

@Ajey 2015-05-18 12:17:21

this fails for '[email protected]'

@adriaan 2015-05-18 13:47:42

Watch out, this is invalid: re.test("[email protected]")

@Rhys van der Waerden 2015-05-29 01:20:21

Also invalid: [email protected] and other new TLDs.

@Mallory-Erik 2015-06-06 09:15:06

김지후@삼성.닷컴 won't work here, nor will any of the new non-Latin-character addresses.

@areeb 2015-07-08 07:14:20

this is invalid for re should be: var re = /^(([^<>()[]\\.,;:\[email protected]\"]+(\.[^<>()[]\\.,;:\[email protected]\"]+)*)‌​|(\".+\"))@(([[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,}))$/;

@WoodyDRN 2015-08-11 08:34:50

Now that we have domains like .ninja .photography and so on, i would add {2,} to the last check: /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]‌​{2,}(?:\.[a-z]{2})?)‌​$/i

@Brian 2015-08-20 21:22:52

@BenRoberts test\\\ is left out in the cold by this regex :(

@Ben Roberts 2015-08-22 03:41:48

@Brian - poor guy is also left out in the cold by Gmail and Apple Mail... :(

@Eric Bishard 2015-08-24 02:01:53

Obviously you cannot validate an email address with JavaScript or RegEx. But I think the answer demonstrates "Here is a somewhat valid way of telling if the jumble of characters entered into an email textbox is most likely an email format. I think it gives someone who would ask this question enough to work with. If they are in fact validating Turkish email they should understand it's limits. Otherwise, use it until you hit a snag and iterate, like every other programmer does!

@PSR 2015-10-15 13:34:44

This validation fails for gmail alias email ids.. ex: [email protected]

@Felipe Skinner 2015-11-06 15:24:37

That answer does not accept a gmail valid email like "[email protected]"

@Soundfx4 2015-11-16 06:40:02

Any support for use of regex checks for e-mails I am 100% against. I'm tired of being told my e-mail address of "[email protected]" is invalid. The best option is to ask the user to type their e-mail in twice and if you MUST use a regex checker, then tell the user that their e-mail address does not appear to be valid and ask if they are sure they typed it right. Even go so far as to point out WHAT did not check out in the regexp check, but do NOT stop them from submitting the form.

@Piskvor 2015-12-07 10:40:17

As for "does not validate" - the first regex throws out about half of this:…, e.g. [email protected] ; note that more TLDs beyond the \.[a-z]{2,8} size were created since 2011. (That's a list of IANA-approved TLDs; I don't care whether someone considers .horse frivolous, I only care if it's canonical - and it is). Edit: Aha, I see that the regex has been completely changed in March.

@madcampos 2016-03-23 14:04:20

this regex use capturing groups, with are not needed in this context and can lead to performance issues.

@Foo 2016-11-13 07:21:52

Try [email protected]. the regex would match :(

@mrid 2017-02-02 09:04:29

the regex is also matching d^&fvf#[email protected] which I guess is not a valid email ID ?

@protspace 2017-02-08 09:59:58

[email protected] = true :)

@maksbd19 2017-04-16 05:35:02

me'[email protected] is valid :) should it be?

@Anders Lindén 2017-05-11 11:03:05

This expression should be updated to not honor email address using ip-addresses instead of domain names, even if those are technically correct.

@nwolybug 2017-05-11 20:08:49

@AndersLindén Using below link for unit test and if ip-address not valid, also account for not honoring the following: [email protected][]…

@Anders Lindén 2017-05-12 06:51:52

@nwolybug The use case of having ip-addresses as part of email addresses is so narrow that it should be omitted.

@Bugfixer 2017-05-25 09:42:06

[email protected] is this a valid email address.

@Liberateur 2017-06-21 08:44:09

Doesn't work for [email protected] and Loïc.Accentué@voilà.fr

@Sumurai8 2017-07-28 14:40:55

@Liberateur As it should. voilà.fr is not a valid domain name. In particular, the à should be encoded with punycode in the domain name. I don't know the actual punycode encoding, but something like Loïc.Accentué will validate... as it should.

@Jerome2606 2018-03-22 13:30:37

Did I make something wrong: new RegExp('^(([^<>()[]\.,;:\[email protected]\"]+(\.[^<>()[]\.‌​,;:\[email protected]\"]+)*)|(\".+\‌​"))@(([^<>()[]\.‌​,;:\[email protected]\"]+\.)+[^<>()‌​[]\.,;:\[email protected]\"]{2,‌​})$', 'i').test('[email protected]') return false ?

@anativ 2018-06-04 07:30:49

This is not valid regex for example æææ pass the regex

@Charly berthet 2018-07-12 08:30:52

Not work with findEmailInStr("sdf ll \ud83c\uddeb\ud83c\[email protected] sdkf")

@WGroleau 2018-08-26 22:20:57

@AndersLindén — Q: What's worse than buggy code telling people they don't know their own address? A: Telling someone he/she should INTENTIONALLY reject valid addresses.

@Ryan Taylor 2012-11-01 14:06:27

Do this:


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:


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

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

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.

More info:

@Kondal 2017-09-25 12:19:11

Is this accepting only lower case

@Ryan Taylor 2017-09-25 19:02:12

@Kondal the javascript code isn't case sensitive because of the /i flag at the end of the regular expression. I mention the fact that it needs to be a case-insensitive compare, but I'll make that more clear.

@B. Bohdan 2019-03-01 16:27:40

There is my version of email validator. This code is OOP-oriented and realized as class with static methods. You will find two versions of validators: strict(EmailValidator.validate) and kind(EmailValidator.validateKind). First throws error if email is invalid and returns email otherwise. Second returns boolean value that says if email is valid. I prefer strict version in most of 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 /^(([^<>()\[\]\\.,;:\[email protected]"]+(\.[^<>()\[\]\\.,;:\[email protected]"]+)*)|(".+"))@((\[[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 email you can follow these ways:

// First way.

try {
    EmailValidator.validate('[email protected]');
} catch (e) {
// Second way.

const email = '[email protected]';
const isValid = EmailValidator.validateKind(email);

if (isValid)
    console.log(`Email is valid: ${email}.`);
    console.log(`Email is invalid: ${email}.`);

@guerreroz 2019-02-23 20:19:12

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!

  $('#submit').on('click', function(){
      var email = $('#email').val();
      var pat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
      if (email.match(pat)){
        return false;
      } else {
        return false;
.input-error {
  border: 1px solid red;
  color: red;

.input-valid {
  border: 1px solid green;
  color: green;
<script src=""></script>
    <input type="text" id="email" placeholder="[email protected]" class="">
    <input type="submit" id="submit" value="Send"/>

@Iman Hejazi 2019-03-04 16:48:07

Have you ever tried DeBounce Email Validation? I suggest taking a look at this.

@ranieribt 2019-01-28 20:49:22

You cold use and simply do:

var validator = require('validator');

validator.isEmail('[email protected]'); //=> true

Note that this can work on the client.

@isapir 2019-01-11 20:04:26

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.!#$%&'*+\/=?^_`{|}~-][email protected][a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}

@Iman Hejazi 2019-03-09 12:44:16

Good. Have you ever tried other validation methods like PHP or API services? Like DeBounce Email Validation Tool.

@Prabhat Kasera 2016-12-22 07:44:49

Best regex ever which conforms with the RFC5322


@Kamil Kiełczewski 2017-09-20 13:53:44

I don't see your regexp in RFC5322: - there is some mistake?

@tecnocrata 2018-12-12 18:05:03

you could also use the New Regex class and make this way:

const validaEmail = function validateEmail(str) { let regex = new RegExp(/([\w\.\-_]+)?\[email protected][\w-_]+(\.\w+){1,}/,'igm') return regex.test(str); }


@Jaymon 2008-09-07 21:21:46

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:

^\[email protected]\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.

@kommradHomer 2012-07-19 07:14:33

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

@user83358 2012-07-30 18:22:53

Squirtle's modified version below seems like the most effective solution on the page. You can validate all you want but I can still enter an email address "".

@Tim Franklin 2013-03-21 04:06:18

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 [email protected], [email protected]@, and [email protected] aren't valid... ^\[email protected]\S+[\.][0-9a-z]+$

@Sam 2013-04-10 23:51:58

I think e-mail addresses can contain spaces. It's probably better to use [email protected]+

@meagar 2015-01-31 14:59:52

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

@meagar 2015-01-31 15:00:18

@MladenJanjetović Yes, the answer specifically states that this is not complete. It is however the best answer. Nobody needs "complete" email validation on the front end. You need to catch the obvious typos and then send a confirmation email.

@gtournie 2015-02-02 15:26:19

@meagar You can be sure that people do that kind of errors ;)

@PhiLho 2015-07-01 16:45:20

@TimmyFranks Bad regex. Beside the minor point you don't need to escape dot in brackets, you invalidate uppercase characters which are valid, so you will get angry users (me, as I like to use them when I write my addresses!)... Beside, it is too restrictive as [email protected][] is a valid e-mail address...

@PhiLho 2015-07-01 17:00:28

@TimmyFranks On a more positive note, you are right on the remark about [email protected]@ (a typo that might happen) and on anchoring the regex. An improvement (still very permissive) would be /^[email protected]\S*([email protected]).$/. The dot isn't even required: an address on a local network can be [email protected] (we have this case on our network!).

@The Muffin Man 2015-07-23 15:22:45

It's so annoying that whenever you bring up email validation you have 99% of people flying off the handle about how it's not accurate to use a regex etc. People, we're not trying to figure out if this is a real email address! We're trying to determine if the syntax is correct!

@Nicu Surdu 2015-10-15 15:31:14

|[email protected]_| - valid email ?

@Mikko Rantalainen 2017-04-06 09:48:46

@Pancho 2017-09-01 09:18:15

While I love the simplicity as a "sense check" approach, just an observation that wrapping it with ^...$ as follows ^\[email protected]\S+$ is an improvement on the above - as it requires entire mail address to conform, not just part of it.

@n1kkou 2018-05-10 21:48:41

Slightly modification to cover more cases like "[email protected]" \[email protected]{1}\S+\.{1}\S+

@Sadee 2018-10-10 10:01:36

@meagar ("áéíóúý@ÁÉÍÓÚÝð") these are so possible to entering to the text field while using mobile phone key pads.

@meagar 2018-10-10 12:15:12

@Sadee I'm not sure what your point is.

@Jonathan 2018-11-13 12:57:43

This comment section sums up why SO has such a bad reputation

@Khaliq Izrail Haxor 2018-11-19 15:33:56

The personal_info part contains the following ASCII characters.

  1. Uppercase (A-Z) and lowercase (a-z) English letters. Digits (0-9).
  2. Characters ! # $ % & ' * + - / = ? ^ _ ` { | } ~
  3. 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)

@Miloš Rašić 2011-03-02 11:26:02

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:

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


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

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

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

  • lastDotPos > 2: There should be at least three characters before the last dot, for example [email protected].

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

@Atul Goyal 2011-07-15 09:24:01

This fn looks nice, but is it better than the regex written in the top answer?

@Miloš Rašić 2011-07-18 16:18:25

I doubt it. I use it only to check whether a string looks like an email and leave the details to server-side code.

@Gennady Shumakher 2012-02-05 10:14:38

It validates OK any string like 'aaaa', i.e. without '@' and '.'

@Miloš Rašić 2012-05-16 16:28:54

It shouldn‘t. lastIndexOf() should return -1 if it does not find the needle.

@Ry- 2014-03-09 20:04:17

“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.” What about "@@"

@trusktr 2014-03-20 08:33:13

"@@" is valid.

@ManoCarayannis 2015-05-14 12:08:08

[email protected] is also valid(?)

@Kavan Fatehi 2018-09-08 11:41:54

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)

@Ali D. 2018-08-21 13:50:45

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:

@C. Lee 2012-02-09 02:22:32

I've slightly modified Jaymon's answer for people who want really simple validation in the form of:

[email protected]

The regular expression:

/\[email protected]\S+\.\S+/

Example JavaScript function:

function validateEmail(email) 
    var re = /\[email protected]\S+\.\S+/;
    return re.test(email);

@user83358 2012-07-30 18:20:04

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!

@OregonTrail 2012-08-09 14:58:13

@ImmortalFirefly, the regex you provided will actually match [email protected] Try pasting your line into a JavaScript console. I believe your intention was to match only the entire text, which would require the beginning of text '^' and end of text '$' operators. The one I'm using is /^[^\[email protected]][email protected][^\[email protected]]+\.[^\[email protected]]+$/.test('[email protected]')

@Ehsan 2014-02-19 07:18:16

Based on this validation this email is valid: [email protected]

@Damian Nikodem 2015-02-24 03:25:40

one of my email addresses is [email protected] , this dosn't allow for the case of machines which are visible to the web/email server directly.

@Bacon Bits 2017-08-17 20:20:19

Hm. Wikipedia says that "[email protected]" is a valid email address. /^[^\[email protected]][email protected][^\[email protected]]+\.[^\[email protected]]+$/.test('"[email protected]‌​om"') // false. Oops.

@hfossli 2017-09-07 08:02:32

Doesn't this also allow @@@[email protected]? :D

@tk_ 2018-04-12 03:27:07

'/\[email protected]\S+\.\S+/.test('[email protected]')' 'true'

@Romain Vincent 2018-11-28 10:30:11

I think the worse part of this simple solution is that it only tests that the pattern is contained. Of course we don't want to end with an overkill regex, but at least make it relevant and add those start and end checks: /^...$/ -- Not like it was making it harder to write ... Discarding additional @ signs is also a good idea

@Micklo_Nerd 2019-04-12 06:19:16

OregonTrail your regex passes [email protected]_com , [email protected] to be true

@Juan Pablo 2018-02-06 20:42:09

Regex update 2018! try this

let val = '[email protected]';
if(/^[a-z0-9][a-z0-9-_\.][email protected]([a-z]|[a-z0-9]?[a-z0-9-]+[a-z0-9])\.[a-z0-9]{2,10}(?:\.[a-z]{2,10})?$/.test(val)) {

typscript version complete

export const emailValid = (val:string):boolean => /^[a-z0-9][a-z0-9-_\.][email protected]([a-z]|[a-z0-9]?[a-z0-9-]+[a-z0-9])\.[a-z0-9]{2,10}(?:\.[a-z]{2,10})?$/.test(val);

more info

@RickS 2018-06-08 20:29:18

This failed for a standard [email protected]

@malimo 2018-11-28 11:37:12

@RickS this simply isn't true. Please check again

@Negin 2017-01-03 05:38:43

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

Here we go :

OR regex:

Regex = /(([^<>()\[\]\\.,;:\[email protected]"]+(\.[^<>()\[\]\\.,;:\[email protected]"]+)*)|(".+"))@[*[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+]*/

@Boldewyn 2012-12-20 15:20:53

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() : /\[email protected]\S+\.\S+/.test(value);

I've put together an example in the fiddle 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.

@Hank 2013-05-02 18:44:23

This is a clever idea to punt on the problem but it doesn't work because browsers have crappy validation as well. E.g. [email protected] validates as true in current versions of Chrome, Firefox, and Safari.

@Boldewyn 2013-05-03 07:02:16

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

@Ronny 2015-04-12 08:51:58

Updated to contain feature detection and graceful degradation, now it doesn't break on new browsers but uses any regex you like.

@Edward Olamisan 2015-05-06 19:13:12

Nice solution. Sadly this is only for HTML5+.

@Woody Payne 2016-02-17 11:49:45

This is by far the best solution to the original question. Yes, it uses HTML5, but the majority of applications that require this level of accuracy will surely already be relying on HTML5 in some other way anyway, so moot point. It's impossible for us to ever determine if someone's email is valid without getting them to verify it anyway, so we really should not be investing so much time or effort into validating it. A quick check for any obvious syntax or attempted naughtiness is all the effort we should be expending.

@Kevin Fichter 2018-07-25 03:10:32

Interestingly, this code returned true for empty strings. I edited it to add a null and empty string check.

@Boldewyn 2018-07-25 06:33:15

Yes, because empty values are allowed, if an input is not required. You could also set input.required = true for the same effect.

@mpyw 2018-07-22 10:53:07

I wrote a JavaScript email validator which is fully compatile with PHP's filter_var($value, FILTER_VALIDATE_EMAIL) implementation.

import validateEmail from 'filter-validate-email'

const value = '...'
const result = validateEmail(value)

is equivalent to:


$value = '...';
$result = (bool)filter_var($value, FILTER_VALIDATE_EMAIL, FILTER_FLAG_EMAIL_UNICODE);

@aabiro 2018-07-18 10:15:54

Here is a solution that works and includes validation/notification fuctionality in a form:

You can run it at this link


(function() {
  'use strict';

  window.addEventListener('load', function() {
    var form = document.getElementById('needs-validation');
    form.addEventListener('submit', function(event) {
      if (form.checkValidity() === false) {
    }, false);
  }, false);


<p class='title'>
    <b>Email validation</b>
  <hr size="30px;">

<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 class="row">
    <div class="col-12">
      <button type="submit" 
          class="btn btn-default btn-block">Sign up now

@bman 2016-12-28 02:51:37

A solution that does not check the existence of the TLD is incomplete.

Almost all answers to this questions suggest using Regex to validate emails addresses. I think Regex is only good for a rudimentary validation. It seems that the checking validation of email addresses is actually two separate problems:

1- Validation of email format: Making sure if the email complies with the format and pattern of emails in RFC 5322 and if the TLD actually exists. A list of all valid TLDs can be found here.

For example, although the address [email protected] will pass the regex, it is not a valid email, because ccc is not a top-level domain by IANA.

2- Making sure the email actually exists: For doing this, the only option is to send the users an email.

@Sbbs 2018-06-21 12:13:20

This is a JavaScript translation of the validation suggested by the official Rails guide used by thousands of websites:


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 protected]');    // true

// Multi-word domains
emailRegex.test('[email protected]');  // true
emailRegex.test('[email protected]'); // true

// Valid special characters
emailRegex.test('unusual+but+valid+email1900=/!#$%&\'*+-/=?^_`.{|}[email protected]') // true

// Trailing dots
emailRegex.test('[email protected]'); // false

// No domain
emailRegex.test('[email protected]');        // false

// Leading space
emailRegex.test(' [email protected]');   // false

// Trailing space
emailRegex.test('[email protected] ');   // false

// Incorrect domains
emailRegex.test('[email protected],com ');   // false

// Other invalid emails
emailRegex.test('')        // false
emailRegex.test('[email protected]') // false
emailRegex.test('[email protected]')       // false

@Vidar 2018-08-14 23:55:43

Doesn't work for [email protected]ø or any other character outside of a-z

@D Prince 2018-06-12 12:03:15

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_\\.\\+-][email protected][a-zA-Z0-9-]+\\.[a-zA-Z0-9-\\.]+";

5) EMAIL_OPTIONAL = "^($|[a-zA-Z0-9_\\.\\+-][email protected][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})?$";

@JoelBonetR 2018-05-28 16:02:31

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, " cannot exists but it may exists an address like that through another provider "[email protected]

Why? According to the RFC:

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. [email protected] is not allowed but "John..Doe" 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 [email protected] and [email protected] might end up in the same inbox as [email protected] or even as [email protected] 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) and (comment)[email protected] are both equivalent to [email protected]

So, i can own an email address like that:

A__z/{it!}[email protected]

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:

For example, this is an RFC valid email:

"very.(),:;<>[]\".VERY.\"[email protected]\\ \"very\".unusual"

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.

@Orchid 2013-11-29 12:26: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

@Toto 2013-11-29 12:32:42

[email protected] is a perfectly valid email that is not recognise by your regex.

@Orchid 2013-12-06 08:09:25

No its not. Correct email pattern is [email protected] , [email protected] does not match that pattern. So, its not a valid address.

@Toto 2013-12-06 08:11:59

@Orchid 2013-12-06 08:19:06

I says email has: [email protected] . And there is '.' in domain part.

@Orchid 2013-12-06 08:21:00

Can you quote a valid actual email of type [email protected]?

@Toto 2013-12-06 08:22:02

Did you the wikipedia page? A TLD is a valid hostname. So [email protected] is a valid email address.

@Orchid 2013-12-06 08:33:03

Well I have never encountered such email, the above verification works fine with me. If you dont want it, just remove dotpos and related clause. It will then work for [email protected] I would suggest verifing email with link if you want to be so sure.…

@Orchid 2013-12-06 08:53:07

And the JQuery validation api also does not accept email of type [email protected]

@Toto 2013-12-06 09:09:05

The only way to validate an email address is to send an email then wait for response. Apart of this, here is an url where you can test if your address is RFC822 compliant: . You can see that [email protected] is a valid address for RFC822.

@pera 2013-09-11 02:21:40

This is how node-validator does it:

/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~][email protected](?:(?:(?:[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])\]))$/

@Colonel Panic 2013-07-14 18:15:44

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.

@eatmypants 2015-04-26 10:14:10

what if there will be more than one '@' symbol? other restricted symbols? This validation cannot be trusted...

@Beep 2017-06-29 10:39:34

Perfect, this answer was simple just a extra layer validation. already have a layer on front end so this helps thanks

@John Montgomery 2019-03-19 00:09:49

This is by far the best answer IMO. Good enough to catch most accidental input (i.e. most things that aren't email addresses) without any false negatives.

@jacobangel 2009-05-02 17:23:03

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.

@Menelaos Kotsollaris 2018-02-28 00:18:21

Here's a simple regex that would just check for the basic format of an email e.g., [email protected]:

\[email protected]\S+\.\S+

Related Questions

Sponsored Content

26 Answered Questions

[SOLVED] What does "use strict" do in JavaScript, and what is the reasoning behind it?

79 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 5663014 View
  • 7038 Score
  • 79 Answer
  • Tags:   javascript arrays

3 Answered Questions

58 Answered Questions

[SOLVED] How do I redirect to another webpage?

33 Answered Questions

[SOLVED] For-each over an array in JavaScript?

46 Answered Questions

54 Answered Questions

[SOLVED] How do I include a JavaScript file in another JavaScript file?

71 Answered Questions

86 Answered Questions

[SOLVED] How do JavaScript closures work?

48 Answered Questions

[SOLVED] Validate decimal numbers in JavaScript - IsNumeric()

Sponsored Content