Guides
Last Updated Apr 12, 2024

Email Validation in JavaScript Using Regex

Elizabeth (Lizzie) Shipton

Table of Contents:

Get your free
API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required
Get your free
Email Verification API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required

Using Regular Expressions in Javascript Email Validation

Once you have your regular expression and you understand enough about regular expressions to know what it does, using it for email validation in your Javascript code is actually very straightforward.

Let’s send your first free
API
Email Verification API
call
See why the best developers build on Abstract
Get your free api

You just need to create a new Regex object and use the provided methods that come on that object to run a search against a provided string. Let's take a look.



const emailRegex = 
 new RegExp(/^[A-Za-z0-9_!#$%&'*+\/=?`{|}~^.-]+@[A-Za-z0-9.-]+$/, "gm");

This creates a new Regex object using the regular expression for email validation that we just broke down and assigns it to a variable called emailRegex. Note that we pass the modifiers in a the second argument to the constructor.



const isValidEmail = emailRegex.test("email_address@domain.com");

console.log(isValidEmail) //true

The Javascript Regex object provides a method called test that accepts a string input and tests it against the regular expression you provided. If the input string is a positive match, the test method will return true. If not, it will return false.

That's it!

Alternative Email Validation Using an API

As we've discussed, you shouldn't use a regular expression to validate an email in Javascript. It is not a robust enough method and will not catch all possible email addresses. Not only that, there are literally hundreds of libraries and packages and APIs out there that will do email validation for you.

Let's look at the AbstractAPI Free Email Validation API as an alternative solution.

Get Started With the API

In order to use the API, you'll need to sign up and get an API key. The API key authenticates you with the API and allows you to make requests.

Navigate to the API home page and click "Get Started"

You'll be asked to sign up with an email address and password. Once you've done that, you'll land on the email API dashboard, where you'll see your API key, links to documentation and pricing modules, and a testing sandbox.

Copy the API key. We'll need it in our Javascript code.

Send an Email Validation Request to the API

Inside your Javascript code, create a function called sendEmailValidationRequest.

This function will accept an email address as its argument. It will send an AJAX request to the API endpoint with the email for validation. It will then receive and analyze the response and return a boolean value.

The response from the API will look something like this:



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

There's a lot of information. For now, we're only interested in the is_valid_format field. The sendValidationRequest function will pull out the value from this field and return it as the result of our function.

Let's take a look at the code:



const API_KEY = "YOUR API KEY";
const API_URL = 
    "https://emailvalidation.abstractapi.com/v1/?api_key=" + API_KEY;

const sendValidationRequest = async (emailAddress) => {
    const fullURL = API_URL + "&email=" + emailAddress;
    const apiResponse = await fetch(fullUrl);
    const data = await apiResponse.json();
    const isValid = data.is_valid_format.value;
    return isValid;
}

This will return false if the email address provided is an invalid email address. If the email validation is successful, it will return true.

Note that the function is an async function, because we are sending a network request. We can improve this somewhat by adding error handling.


const sendValidationRequest = async (emailAddress) => {
    try {
        const fullURL = API_URL + "&email=" + emailAddress;
        const apiResponse = await fetch(fullUrl);
        const data = await apiResponse.json();
        const isValid = data.is_valid_format.value;
        return isValid;
    } catch(error) {
        throw new Error("Unable to validate email");
    }
}

This is a very easy way of validating email in your Javascript app.

The AbstractAPI endpoint does a lot of checks when it receives your email. As well as running a much more sophisticated regular expression check on the email, it also checks for syntax errors and typos in the email address (for example john@agmil.com), does real-time SMTP and MX record checks against the email's domain, and uses a variety of filters backed by machine learning to detect risky emails.

4.9/5 stars (7 votes)

Elizabeth (Lizzie) Shipton
Lizzie Shipton is an adept Full Stack Developer, skilled in JavaScript, React, Node.js, and GraphQL, with a talent for creating scalable, seamless web applications. Her expertise spans both frontend and backend development, ensuring innovative and efficient solutions.
Get your free
Email Verification API
API
key now
Validate & verify emails instantly using Abstract's API.
get started for free

Related Articles

Get your free
API
Email Verification API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required