How to validate an email address in JavaScript

Last Updated Dec 29, 2020
Emma Jagger

Engineer, maker, Google alumna, CMU grad

The common point between new accounts signing-up to your service and subscribing to your mailing list is that they identify themselves with an email address.

If we were in a perfect world, all the email addresses would be and remain valid, but with time mailboxes got closed, and the addresses in your database become invalid. There is also always the possibility for people to make a typo while entering their email addresses, and some of them may also voluntarily use a fake address.

This is why a list must regularly be cleaned and invalid addresses deleted to preserve its quality, optimize your mailings' deliverability rate, and increase your email marketing campaigns' success.

Verify an email address in JavaScript using regular expressions

You may want to implement a simple email address format validator on the client-side, so when your visitors enter their email address in your forms, the address format gets validated before reaching your server.

Using regular expression is probably the best approach. Let’s see the most simple syntax:

c

function validateEmail(email) {
  const re = /^\S+@\S+$/;
  return re.test(String(email).toLowerCase());
}

This is a breakdown of the regular expression /^\S+@\S+$/:

  • ^ a the beginning of a regexp: match the start of the string
  • \S+ match one or more non-whitespace characters
  • @ match the sign "@"
  • \S+ match one or more non-whitespace characters
  • $ match then end of the string

This regular expression verifies that the email address contains no space and is composed of one or more characters followed by the "@" sign followed by one or more characters.

This seems to be enough for most email addresses, but in reality, it would reject some valid email because whitespace characters are actually allowed as long as they are escaped. For example, the following is a valid email and would be rejected by the code mentioned above:


"very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@strange.example.com

At this point, you may want to continue in the same direction and try to complexify this regular expression and consider every case. For example, you could try to match escaped or quoted whitespaces. If you do so, you will also have to implement all specific cases, including Unicode characters and much more. Then you will end up with a regexp impossible to debug and particularly impossible to test.

How to efficiently validate an email address

As demonstrated above, efficiently verifying an email address format by yourself is not an easy task.

The only reliable way to verify an email address is to have the recipient’s SMTP server to validate it. And to do so, an email validator would need to go through the following steps: validate the domain name, search through its MX records, and query the SMTP servers.

Using Abstract API to validate an email address

Abstract provides an API that solves this problem and takes away the complexity of this task. With a single call, you can validate the address format, check if the email is hosted on a free service if it is a disposable email, and much more.

After creating a free account at Abstract, which automatically generates your private API key, you can call the API and validate your visitors’ email addresses very easily.

Implementation example in JavaScript:

c


function httpGetAsync(url, callback) {
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.onreadystatechange = function() {
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
      callback(xmlHttp.responseText);
  }
  xmlHttp.open("GET", url, true); // true for asynchronous
  xmlHttp.send(null);
}

var url = "https://emailvalidation.abstractapi.com/v1/?api_key=YOUR-API_KEY&email=EMAIL_TO_VERIFY"

httpGetAsync(url)

This is an example of a response:



{
  "email": "johnsmith@gmail.com",
  "autocorrect": "",
  "deliverability": "DELIVERABLE",
  "quality_score": 0.90
  "is_valid_format": {
        "value": true,
        "text": "TRUE"
        },
  "is_free_email": {
        "value": true,
        "text": "TRUE"
        },
  "is_disposable_email": {
        "value": false,
        "text": "FALSE"
        },
  "is_role_email": {
        "value": false,
        "text": "FALSE"
        },
  "is_catchall_email": {
        "value": false,
        "text": "FALSE"
        },
  "is_mx_found": {
        "value": true,
        "text": "TRUE"
        },
  "is_smtp_valid": {
        "value": true,
        "text": "TRUE"
        }
}

Abstract's Email Validation API comes with Javascript libraries, code snippets, guides, and more.
Get started