Guides
Last updated
July 20, 2025

5 Ways to Implement Email Validation in Yup

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

Proper email validation is a key part of building forms with Yup. Here are five distinct methods for implementation, each with working code. You'll see the common shortcomings of these traditional approaches and how Abstract API helps overcome them for more reliable validation.

How to Implement Email Validation in Yup

Here are four common methods to validate emails in Yup, from simple built-in functions to more complex asynchronous checks, complete with code examples for each approach.

Built-in string().email()

The simplest approach is to use the built-in email() method. This function attaches Yup’s default regex to your validation schema. It uses the same pattern that browsers employ for an input field with type="email".

This default pattern is intentionally permissive, so it catches obvious formatting errors with no extra configuration. Note that email() does not treat an empty string as invalid unless you also chain the required() method. Without it, an empty string will pass validation.

import * as yup from 'yup';  
  const schema = yup.object({  
    email: yup.string().email('Malformed').required()  
  });

Explicit regex with matches()

For more control, you can provide your own regular expression with the matches() method. This lets you drop in any regex pattern to enforce stricter validation rules.

For example, a tight pattern can forbid double dots in the domain, require a public suffix, or lock the domain to specific company-internal zones. If you need to allow optional emails without a separate required() call, you can use the excludeEmptyString flag.

const EMAIL_RE = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i;  
  const schema = yup.object({  
    email: yup.string().matches(EMAIL_RE, 'RFC-like').required()  
  });

Delegation to validator.js through test()

You can delegate validation logic to an external library like validator.js by use of the test() method. The validator.js library ships a battle-tested implementation that follows RFC 5322 edge cases better than most custom regex patterns.

The test() function receives the raw input value and runs your custom predicate function on it. It can also reuse Yup’s built-in interpolation system to generate the error message if validation fails.

import isEmail from 'validator/lib/isEmail';  
  const schema = yup.object({  
    email: yup.string()  
      .required()  
      .test('is-valid', '${path} invalid', v => isEmail(v ?? ''))  
  });

Asynchronous verification inside test()

The test() method also supports asynchronous operations. If you return a Promise from the test() function, the entire Yup schema becomes asynchronous. Yup will wait for the network call to resolve before it completes the validation.

This allows you to check MX records, run a uniqueness query against a database, or consult a suppression list before you accept the value. Because the validation is now async, synchronous callers like validateSync() will throw an error, so you must use validate() instead.

const schema = yup.object({  
    email: yup.string().required().test(  
      'exists',  
      'Address unreachable',  
      async v => {  
        if (!v) return false;  
        const res = await fetch(`/api/email/verify?e=${encodeURIComponent(v)}`);  
        return (await res.json()).deliverable;  
      }  
    )  
  });
 

Challenges of Email Validation in Yup

While these methods offer some control, they introduce significant drawbacks. The reliance on regular expressions and local checks leads to both false positives and false negatives, which complicates reliable email validation.

  • The RFC email grammar is complex. Regex-based methods like string().email() or a custom matches() pattern often fail to cover edge cases like comments or international characters. This creates false negatives where valid addresses get rejected.
  • The default regex in string().email() is outdated. It allows malformed characters and fails to handle newer top-level domains or punycode correctly. This weakness means some invalid email addresses can pass validation, which creates false positives.
  • Yup only validates the email's format, not its existence. Methods like string().email() cannot detect disposable inboxes, spam traps, or domains without MX records. These addresses pass validation but will fail upon delivery, which results in false positives.
  • To tighten validation rules, you must write a custom test() function or replace the regex. This approach effectively reinvents email validation, which increases maintenance costs and can cause inconsistencies across different services that use the same schema.

Validate Emails with Abstract API
Implement strong email validation with Yup to ensure the quality and accuracy of user data.
Get started for free

How Abstract API Handles Email Validation in Yup

The Abstract API addresses the core weaknesses of traditional validation methods. It uses multi-layer checks and real-time data to improve accuracy.

  • It performs multi-layer checks that include syntax, typo correction, MX records, SMTP, and a machine-learning-based risk score.
  • It provides a real-time deliverability flag and a numeric quality score to inform rejection or throttling logic.
  • It detects disposable, role-based, free-provider, and catch-all emails to help block or triage risky sign-ups.

How to Bring Abstract API to Your Dev Environment

Once you know Abstract’s capabilities, it is simple to add its email validation API to your project.

  • Install Yup and Axios with the command: npm i yup axios.
  • Create a free Abstract account to copy your Email Validation API key.
  • Add the ABSTRACT_KEY to your dot-env file or secret manager.
  • Write a helper function that calls the Abstract API endpoint with your api_key and the user's email.
  • Add a Yup async test that awaits the helper and confirms the email's deliverability.
  • Use the schema in your controller, Formik form, or service layer.

Sample Email Validation Implementation with Abstract API

This code defines an asynchronous function, checkEmail, that sends a user's email to the Abstract API endpoint. It then returns a boolean value. The function confirms if the email's deliverability status is 'DELIVERABLE' and that it is not a disposable address. The Yup schema uses this function in a custom test to validate the email field beyond a simple syntax check.

import axios from 'axios';
import * as Yup from 'yup';

const checkEmail = async email => {
  const { data } = await axios.get('https://emailvalidation.abstractapi.com/v1', {
    params: { api_key: process.env.ABSTRACT_KEY, email }
  });
  return data.deliverability === 'DELIVERABLE' && !data.is_disposable_email.value;
};

export const schema = Yup.object({
  email: Yup.string()
    .required('email required')
    .email('syntax wrong')
    .test('abstract', 'email not deliverable', value => checkEmail(value))
});

A successful API call returns a detailed JSON object like this:

{
  "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" }
}

The API response provides clear data points for your application logic. The deliverability and quality_score fields tell you whether to accept, refuse, or flag an email. Other booleans like is_disposable_email and is_role_email give you fine-grained control for filters. The API can also suggest corrections for user typos.

Final Thoughts

Traditional email validation in Yup relies on regex, which cannot detect invalid domains or disposable addresses. This gap creates false positives and security risks.

Abstract API closes this gap with real-time, multi-layer checks that confirm actual deliverability. For reliable user email validation, consider an account on Abstract API to get your free API key.

Validate Emails with Abstract API
Ensure your forms collect valid emails by implementing proper validation with your Yup schemas.
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