Validate an email address in JavaScript
Published on Jan 26, 2020
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
/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.
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.
if (email.indexOf('@') > 0) {
console.log('Good enough');
}
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.
Tags: validation | JavaScript | email | regex