How to validate an email address in JavaScript

published: 25 Apr 2022

2 min read

How to validate an email address in JavaScript

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('foo@bar.com')) // true
console.log(validate('foo+foo@bar.com')) // true
console.log(validate('foo @bar.com')) // false
console.log(validate('{a}!%?@@bar.com')) // 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('foo@bar.com') // true
validator.isEmail('foo#!@@bar.com') // false

How to validate an email address in JavaScript | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, nodejs, programming
Check out what's on in the tag: javascript, nodejs, programming, validate