Guides
Last updated
July 20, 2025

5 Ways to Implement Email Validation in JavaScript

Nicolas Rios
Nicolas Rios
Table of Contents:
ON THIS PAGE
Get your free
email validation
 API key now
stars rating
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

Validating email addresses in JavaScript is a key step for maintaining data quality. We'll explore five ways to do this with working code snippets, examine the pitfalls of traditional methods, and see how Abstract API provides a more complete solution that addresses these shortcomings.

How to Validate an Email Address in JavaScript

This section covers five common methods for email validation. Each approach uses a different technique, from native browser features to external libraries and DNS checks.

HTML Constraint Validation API

This method uses the browser’s built-in parser that supports the <input type="email"> element. JavaScript's role is to trigger the validation check, not to maintain a complex pattern.

The browser’s implementation applies the WHATWG email grammar and automatically flags mismatches. The `checkValidity()` method on the input element returns a boolean that indicates if the email is valid.

<input id="mail" type="email" required>
<script>
function isValid() {
const el = document.getElementById('mail');
return el.checkValidity(); // boolean
}
</script>

A Single Regular Expression

This technique employs a single, complex regular expression that approximates the RFC 5322 standard. It is a pragmatic pattern designed to cover most production addresses, including quoted local parts and domain literals, as noted in online discussions.

The code defines a constant, `rfc5322`, which holds the pattern. The `test()` method of this regular expression is then called with the email address to return a true or false value.

const rfc5322 = /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:25[0-5]|2[0-4]\d|[01]?\d\d?)(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d\d?)){3}\])$/i;

function isValid(email) {
return rfc5322.test(email);
}

The Validator.js Library

Another approach is to use a dedicated NPM package like `validator`. This library includes a maintained `isEmail` function that you can import into your project.

It offers several options, such as the ability to allow IP addresses in the domain, permit UTF-8 characters in the local part, and define a blacklist of hosts. The library works in both browser and Node.js environments.

import validator from 'validator';
validator.isEmail(addr, {
allow_ip_domain: true,
allow_utf8_local_part: true,
host_blacklist: ['example.com']
});

Live MX Record Check

This method checks if an email address's domain is configured to receive mail. It queries for the domain's Mail Exchange (MX) records.

The code sends a request to a DNS over HTTPS (DoH) endpoint that supports Cross-Origin Resource Sharing (CORS). A successful response with an "Answer" array indicates the domain has a valid MX record.

The `validate` function first extracts the domain from the email address. It then calls the `hasMx` function to perform the DNS lookup.

async function hasMx(domain) {
const url = `https://dns.google/resolve?name=${domain}&type=MX`;
const res = await fetch(url);
const { Answer } = await res.json();
return Array.isArray(Answer) && Answer.length > 0;
}

async function validate(email) {
const [, domain] = email.split('@');
return await hasMx(domain);
}

Challenges of JavaScript Email Validation

While the methods above offer starting points, they come with significant drawbacks. Effective email validation requires more than a pattern match, as many approaches fail to account for real-world deliverability and standards.

  • A single regular expression cannot fully cover the complex RFC 5322 grammar. This approach leads to unreadable patterns that either reject valid mailboxes or permit invalid ones, a significant drawback for the single regex method.
  • Client-side checks, like the HTML Constraint Validation API, cannot confirm deliverability. They lack the ability to perform DNS or MX record lookups, so they approve addresses at domains that cannot actually receive mail.
  • Most validation methods, including simple regular expressions and the HTML API, ignore internationalization rules. They often break on valid global addresses that use Unicode characters in the local part or punycode for the domain name.
  • Email providers define their own local-part rules, like case sensitivity or support for tags. A fixed client-side rule, whether from a regex or a library like Validator.js, risks the rejection of valid user addresses.

Validate Emails with Abstract API
Implement email validation in your JavaScript project to ensure you're collecting accurate user data.
Get started for free

How Abstract API Handles Email Validation in JavaScript

Abstract API addresses the core weaknesses of traditional methods. It adds a network layer that performs comprehensive checks beyond simple string validation.

  • Traditional regex or HTML5 checks only confirm a string's format. They cannot tell if a domain exists or if the mailbox can receive mail.
  • The API runs multiple checks, which include syntax validation, typo correction, disposable provider lookups, and MX record discovery. It also performs an SMTP handshake.
  • This process removes complex DNS, SMTP, and list-maintenance code from your service. It also cuts sign-up latency and reduces bounce-rate risk.
  • The API uses HTTP and is stateless. You can call it from a browser, Node, or edge functions without extra dependencies.

How to Add Abstract API to Your Dev Environment

Once you know Abstract’s capabilities, you can add its email validation API to your project with ease.

  • Create a free Abstract account and copy your Email Validation API key.
  • Install a request library like Axios with `npm i axios`, or use the native Fetch API.
  • Store the key in an environment variable, for example, ABSTRACT_API_KEY.
  • Write a helper function that calls the API endpoint with your key and the target email.
  • Parse the JSON response to gate user flows based on deliverability status.
  • Implement retry logic and a short timeout to handle network issues.
const axios = require('axios');
const { ABSTRACT_API_KEY } = process.env;

async function validateEmail(email) {
const url = `https://emailvalidation.abstractapi.com/v1/?api_key=${ABSTRACT_API_KEY}&email=${encodeURIComponent(email)}`;
const { data } = await axios.get(url, { timeout: 3000 });
return data;
}

module.exports = validateEmail;

Sample Email Validation Implementation with Abstract API

The function contacts the API and returns a detailed JSON object. This response provides a clear deliverability status, a quality score, and boolean flags for disposable services, role accounts, and catch-all domains. This data lets you make a single, informed decision about an email's validity.

Below is a sample response for a valid email address.

{
"email": "johnsmith@gmail.com",
"autocorrect": "",
"deliverability": "DELIVERABLE",
"quality_score": 0.9,
"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" }
}

Final Thoughts

Traditional validation methods only check format. They cannot detect if a domain is real or if an inbox can receive mail. Abstract API performs deep checks, from syntax and typos to SMTP handshakes, for a complete picture of email quality. To reliably validate user emails, get a free API key from Abstract API.

Validate Emails with Abstract API
Improve your data quality by adding simple and effective email validation to your JavaScript project.
Get started for free

Related Articles

Phone Validation
key now
Get your free
stars rating
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