All Articles

How to validate an email in JavaScript

In general, this is not a good idea to use a regular expression to validate an email address in JavaScript. You need to think more about the user flows before adding such validations. More accurate option for validations:

  • Ask the user type the email twice.
  • Use a regex checker. Ask him to double-check the email, if there are some problems in the checker.
  • Don’t stop users submit forms. There are no 100% solutions to validate emails with regular expressions in JavaScript.

If you are okay with these points, there is an option:

function validateEmail(email) {
  const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  return re.test(String(email).trim().toLowerCase());
}

// Logs true
console.log(validateEmail('ñoñó4@test.com'));

// Logs true
console.log(validateEmail('a@a.aa'));

// Logs false
console.log(validateEmail('a@a.a'));

// Logs false
console.log(validateEmail('a..@a.aa'));