How to validate an email address in JavaScript

It can be difficult to validate an email address. There are many valid but complex email addresses. It is impossible to tell whether an email address is valid. You can only send the email to see if it bounces. With this in mind, there are a few things you can do to improve the user’s experience. We’ll be discussing some of the most common methods JavaScript uses to validate email addresses.

First, I think it’s safer to make an error on the permissive side when validating email address. I would rather allow a few false email addresses to pass than reject a valid address. Front-end email validation does not verify if the email address has validity. It is only about validating the syntax. We will start with the most permissive solution first and work our ways to the other end.

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

RegEx is a way to test for basic email addresses.  _@_._.  This is what I assume about email addresses. If an email address is not in this format, it’s likely that they have made a mistake.

The Regex above will fail on the following format:  _@_@._.We can fix this by changing our Regex.

function emailIsValid (email) {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)
}

emailIsValid('tyler@tyler@ui.dev') // false
emailIsValid('tyler@ui.dev') // true

That’s all. Anything more than this will be considered opinionated. If the above solutions don’t work, you can search for other solutions. However, I recommend that you rethink your approach.