Ensuring email addresses are valid in Yup is a fundamental step for clean data. We'll walk through five different implementation methods, providing code for each. Then, we'll examine the common shortcomings of these techniques and introduce how Abstract API overcomes them for more reliable validation.
How to Implement Email Validation in Yup
Here are three common methods to validate email addresses with Yup. Each approach offers a different level of control and complexity for your data validation schemas.
The Built-in string().email() Method
The "email()" function attaches Yup’s default regex, which is the same pattern browsers use for an email input field. This method catches obvious formatting errors with no extra configuration, as shown in the npmjs.com documentation. Because the pattern is intentionally permissive, some invalid strings like “user@example.com..au” may pass.
The "email()" function also does not treat an empty string as invalid. To flag empty strings, you must also chain the "required()" function, a detail noted in a discussion on Lightrun.
import * as yup from 'yup';
const schema = yup.object({
email: yup.string().email('Malformed').required()
});
Explicit Regex with matches()
The "matches()" function allows you to use any custom regular expression for validation. A tight pattern can enforce stricter rules, such as to forbid double dots, require a public suffix, or lock the domain to internal zones. If you need to allow optional emails without a separate "required()" call, you can use "excludeEmptyString", as suggested by the package documentation.
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 with test()
You can delegate validation to an external library like "validator.js" through the "test()" function. The "validator.js" library provides a battle-tested implementation that follows RFC 5322 edge cases better than most ad-hoc regular expressions. The "test()" function receives the raw value and runs your predicate.
It can also reuse Yup’s interpolation system for the error message, a feature highlighted in a GitHub issue discussion. This approach combines the robustness of a specialized library with the declarative structure of Yup.
import isEmail from 'validator/lib/isEmail';
const schema = yup.object({
email: yup.string()
.required()
.test('is-valid', '${path} invalid', v => isEmail(v ?? ''))
});
Challenges of Email Validation in Yup
While these methods offer basic checks, they present significant challenges. The limitations of regular expressions and local validation often lead to both false positives and false negatives, undermining data quality.
- The built-in email method uses an outdated regex. It rejects valid but uncommon addresses with comments or international characters, and it accepts malformed strings with invisible characters or new top-level domains.
- All local validation, including the built-in email and matches methods, only confirms the string's format. It cannot detect non-existent domains, temporary inboxes, or spam-trap addresses, which leads to subsequent delivery failures.
- A custom regex with the matches method struggles with the full RFC grammar. Developers often write patterns that incorrectly block valid addresses that contain quotes or comments, which creates a poor user experience.
- To tighten rules, one must write a custom test function or replace the regex. This approach adds maintenance costs and introduces inconsistencies if multiple services depend on the same shared validation 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
Abstract API addresses the core weaknesses of traditional validation methods through multi-layer checks that extend beyond simple syntax rules.
- It performs multi-layer checks for syntax, typos, MX records, and SMTP responses, and it provides a risk score based on machine learning.
- It provides a real-time deliverability flag and a numeric quality score to inform rejection or throttling logic.
- It detects disposable, role-based, and catch-all email addresses so you can block or triage risky sign-ups.
How to Bring Abstract API to Your Dev Environment
Once you understand Abstract’s capabilities, you can add its email validation API to your project with a simple process.
- Install Yup and Axios with npm.
- Create a free Abstract account and copy your Email Validation API key.
- Add your ABSTRACT_KEY to a dot-env file or secret manager.
- Write a helper function that calls the Abstract API endpoint with your key and the user's email.
- Add an asynchronous Yup test that awaits the helper and checks for a "DELIVERABLE" status and a non-disposable address.
- Use the schema in your controller or form. Yup will reject the promise if the API flags the address as risky.
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))
});
Sample Email Validation Implementation with Abstract API
The code above defines a function, checkEmail, that sends a user's email to Abstract API. It returns "true" only if the API confirms the address is "DELIVERABLE" and not disposable. This function integrates into a Yup schema via the asynchronous .test method. This process layers real-time deliverability checks on top of Yup’s standard syntax validation.
The API returns a detailed JSON object. Key fields like "deliverability" and "quality_score" tell you whether to accept, refuse, or flag an email. Other boolean flags for disposable, role-based, or catch-all addresses give you fine-grained control to filter sign-ups and protect your platform.
{
"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 email validation often relies on syntax checks that approve undeliverable or temporary addresses. This method creates gaps for bad data and potential fraud.
Abstract API closes these gaps with real-time checks for deliverability and address type. For reliable user validation, create a free account on Abstract API and get your 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