How can I validate an email address in JavaScript?
Solution 1
Using regular expressions is probably the best way of validating an email address in JavaScript. View a bunch of tests on JSFiddle taken from Chromium.
const validateEmail = (email) => {
return String(email)
.toLowerCase()
.match(
/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|.(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
);
};
The following is an example of a regular expression that accepts unicode.
const re =
/^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
Keep in mind that one should not rely on JavaScript validation alone, as JavaScript can be easily disabled by the client. Furthermore, it is important to validate on the server side.
The following snippet of code is an example of JavaScript validating an email address on the client side.
const validateEmail = (email) => { return email.match( /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ ); };
const validate = () => { const $result = $(‘#result’); const email = $(‘#email’).val(); $result.text(”);
if(validateEmail(email)){ $result.text(email + ’ is valid.’); $result.css(‘color’, ‘green’); } else{ $result.text(email + ’ is invalid.’); $result.css(‘color’, ‘red’); } return false; }
$(‘#email’).on(‘input’, validate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="email">Enter email address</label>
<input id="email" type="email">
<p id="result"></p>
Solution 2
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@]+$/
The above regexes match the whole string, remove the leading and ^
and trailing $
if you want to match anywhere in the string. The example below matches anywhere in the string.
If you do want to match the whole sring, you may want to trim()
the string first.
Example JavaScript function:
function validateEmail(email) { var re = /\S+@\S+\.\S+/; return re.test(email); }
console.log(validateEmail(‘my email is anystring@anystring.any’)); // true
console.log(validateEmail(‘my email is anystring@anystring .any’)); // false
Solution 3
Just for completeness, here you have another RFC 2822 compliant regex
The official standard is known as RFC 2822. It describes the syntax that valid email addresses must adhere to. You can (but you shouldn't — read on) implement it with this regular expression:
(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])
(...) We get a more practical implementation of RFC 2822 if we omit the syntax using double quotes and square brackets. It will still match 99.99% of all email addresses in actual use today.
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?
A further change you could make is to allow any two-letter country code top level domain, and only specific generic top level domains. This regex filters dummy email addresses like
asdf@adsf.adsf
. You will need to update it as new top-level domains are added.
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum)\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
Solution 4
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+$/
Solution 5
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.