validation is hard. With the vast amount of complex, but valid email addresses that exist today, the only way to truly tell if an email address is valid is to send the email and see if it bounces. With that said, there are a few things we can do on the front end to make the experience better for everyone. In this post we’ll talk about few common approaches for validating email addresses in JavaScript.

when validating email addresses I believe it’s better to error on the permissive side. I’d much rather let pass a few fake email addresses than reject a valid one. Front-end email validation is about figuring out if the syntax is correct, not if the email address is valid. With that said, we’ll start off with the most permissive solution and work our way towards the other end.

function emailIsValid (email) {
return /\S+@\S+\.\S+/.test(email)
}

If you’re not familiar with RegEx, /\S+@\S+\.\S+/ is testing for the most basic email address structure, _@_._. That’s typically all I ever assume about an email address. If the email the user types in doesn’t follow that structure, odds are they made a typo.

One issue with the Regex above is it’ll fail on this format: _@_@._. To fix that, we can change up our Regex a bit.

function emailIsValid (email) {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)
}
emailIsValid('tyler@tyler@ui.dev') // false
emailIsValid('tyler@ui.dev') // true

That’s it. Anything beyond this is going to be too opinionated. You could find some other solutions by googling around but I recommend re-thinking your approach if the above examples don’t work for you.


Before you leave

I know, "another newsletter pitch" - but hear me out. Most JavaScript newsletters are terrible. When's the last time you actually looked forward to getting one? Even worse, when's the last time you actually read one rather than just skim it?

We wanted to change that, which is why we created Bytes. The goal was to create a JavaScript newsletter that was both educational and entertaining. 84,512 subscribers and an almost 50% weekly open rate later, it looks like we did it.

Delivered to 84,512 developers every Monday

Avatar for Tyler McGinnis

Tyler McGinnis

CEO of ui.dev. Obsessed with teaching, writing, swimming, biking, and running.

Share this post