regex - What's the best way to validate an email address in JavaScript?

ID : 54

viewed : 223

Tags : javascriptregexvalidationemail-validationjavascript

Top 5 Answer for regex - What's the best way to validate an email address in JavaScript?

vote vote

94

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

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

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

const validateEmail = (email) =>   return email.match(     /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/   ); };  const validate = () => {   const $result = $('#result');   const email = $('#email').val();   $result.text('');    if (validateEmail(email)) {     $result.text(email + ' is valid :)');     $result.css('color', 'green');   } else {     $result.text(email + ' is not valid :(');     $result.css('color', 'red');   }   return false; }  $('#email').on('input', validate); 

And this is the html:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <label for="email">Enter an email address: </label> <input id="email" /> <h2 id="result"></h2> 
vote vote

85

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

anystring@anystring.anystring 

The regular expression:

/\S+@\S+\.\S+/ 

To prevent matching multiple @ signs:

/^[^\s@]+@[^\s@]+\.[^\s@]+$/ 

Example JavaScript function:

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

vote vote

80

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

vote vote

69

Wow, there are lots of complexity here. If all you want to do is just catch the most obvious syntax errors, I would do something like this:

^\S+@\S+$ 

It usually catches the most obvious errors that the user makes and assures that the form is mostly right, which is what JavaScript validation is all about.

EDIT: We can also check for '.' in the email using

/^\S+@\S+\.\S+$/ 
vote vote

51

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.

Top 3 video Explaining regex - What's the best way to validate an email address in JavaScript?

Related QUESTION?