In JavaScript, the best way to reliably verify that a string is a valid email is by using a regular expression. Here’s how it’s done.
If I were to ask you what’s the most characteristic sign of an email address, you’d probably say it’s the @
character.
But having an @
sign alone in a string wouldn’t make it a valid email address.
You should at least consider the following:
- there should be a single
@
sign - there should be a dot
.
- the
@
sign should be placed before the dot - there should be some characters before the
@
sign - there should be some characters between the
@
sign and the dot - there should be some characters (not too many!) after the dot
And there are quite a few other rules.
So, rather than thinking of a long chain of if
statements, I suggest writing a regular expression
to test your string.
For convenience, I’ll wrap the regex into a function that accepts an email address as a string and return the boolean value that shows if that string is an email or not.
const validateEmail = (email) => new RegExp(
/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/).test(email);
This regular expression isn’t taking into consideration the allowed domains and will return true for an
email address like [email protected]
.
If you want to limit certain domain extensions, you can do it like this.
const validateEmail = (email) => new RegExp(
/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|io)\b/).test(email);
Now the function validateEmail
returns true
only for properly formatted email addresses that end with
com
, org
, net
or io
.