Email 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.

First, 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.