There are multiple ways to validate an email address in JavaScript. The best option to validate an email address is by using a regular expression.

The latest official standard for email validation is called RFC 5322. It describes the syntax a valid email address must adhere to.

The following regular expression conforms to the RFC 5322 standard and matches simple email addresses.

([-!#-'*+/-9=?A-Z^-~]+(\.[-!#-'*+/-9=?A-Z^-~]+)*|"([]!#-[^-~ \t]|(\\[\t -~]))+")@([-!#-'*+/-9=?A-Z^-~]+(\.[-!#-'*+/-9=?A-Z^-~]+)*|\[[\t -Z^-~]*])

Here is a function that accepts a string as input and returns whether it is a valid email address or not using the above regular expression:

const validate = email => {
  const expression =
    /([-!#-'*+/-9=?A-Z^-~]+(\.[-!#-'*+/-9=?A-Z^-~]+)*|"([]!#-[^-~ \t]|(\\[\t -~]))+")@([-!#-'*+/-9=?A-Z^-~]+(\.[-!#-'*+/-9=?A-Z^-~]+)*|\[[\t -Z^-~]*])/i

  return expression.test(String(email).toLowerCase())

console.log(validate('')) // true
console.log(validate('')) // true
console.log(validate('foo')) // false
console.log(validate('{a}!%?')) // false

While the above method satisfies all the frequent use cases, it is not 100% accurate. One can assume that it will work for 99.99% of all email addresses in actual use today.

Note: You should not always rely upon JavaScript validation. One can easily disable JavaScript in the browser. Instead, you should always re-validate email addresses on the server side to make sure it is correct.

Email validation in HTML5

HTML5 itself has email validation. You can set the input type to email with required attribute to kick off the validation:

<input type="email" name="email" placeholder="Email Address" required>

Email validation in Node.js

You can reuse the above JavaScript function to validate email addresses in Node.js. This is an advantage of using JavaScript on both client-side and server-side.

Alternatively, you could also use pre-built packages like validator to perform email validation in Node.js:

const validator = require('validator')

validator.isEmail('') // true
validator.isEmail('foo#!') // false

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.