How to Validate an Email Address in JavaScript

In this short tip post, we will learn how to validate an email address in JavaScript using Regular expressions.

Objective

Validate the input email address using Regular expression in plain JavaScript.

Approach

Email addresses are consists of two parts:

  1. Local part
  2. Domain part

Local part can be a combination of strings, numbers and alphanumeric and so is the domain. The best way is to validate the combinations of such string is using Regular expression.

We are going to use the Regular expression suggested by RFC to cover 99.99% of email addresses.

Code

Here is the function in JavaScript to help you validate an email address.

function validateEmailAddress(email) {
        var expression = /(?!.*\.{2})^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")@(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;
return expression.test(String(email).toLowerCase());
}

let test1 = validateEmailAddress('[email protected]'); // true
let test2 = validateEmailAddress('shahid@codeforgeek'); // false

Check out the codepen for the live demo.

See the Pen
validate email address
by Shahid Shaikh (@codeforgeek)
on CodePen.

Love JavaScript? Learn more about it here.

Suggestion

You can’t truly validate the email address just using JavaScript. Follow these steps to validate the each aspect of the email address validation.

  1. Use the HTML5 email type input to accept email address
  2. Use regular expression to validate the address
  3. Use email verification API Services to validate the MX record and domain name validity
  4. Send the email with the confirmation link to fully validate the email address
Pankaj Kumar
Pankaj Kumar
Articles: 209