Validate an email address in JavaScript

V

This is my least favorite topic; validating email addresses. There are hundreds of examples using regular expressions that are all slightly different and all have there own quirks with them.

If validation must be done, I suggest only doing this on the client-side. Ideally the server-side performs email validation by sending an actual email that includes a unique link to validate the email is valid.

But if JavaScript is a must, here is the best one I’ve found.

Regular Expression to validate email

[code]
/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.
[/code]

This regular expression is taken from W3C which gives me a bit more confidence in it being as robust as possible.

Now for me personally, I’d go even simpler in literally checking for only an @ symbol because that is legitimately the bare minimum that is required in every email address.

[code]
if (email.indexOf(‘@’) > 0) {
console.log(‘Good enough’);
}
[/code]

I am aware that indexOf is zero-based so if the first value was an @ this would not pass. I’m ok with that because it also at least asserts there is a minimum of 1 character before the @.

As long as the server-side takes care of the real validation, I’m good with the most simple check possible.

About the author

By Jamie

My Books