Validating email addresses in HTML is a key part of maintaining clean data. We will explore three common ways to add this check, providing working code for each. Then, we'll look into the pitfalls of these methods and show how Abstract API effectively addresses them.
How to Implement Email Validation in HTML
These methods use built-in browser features and JavaScript to check email addresses directly within your HTML form. This improves user experience and helps maintain data quality from the start.
The Native Input Element
HTML5 provides a specific input type for email. When you set the "type" attribute to "email", the browser automatically checks the input against standard email syntax without any need for JavaScript. The browser parses the value based on WHATWG email grammar.
It exposes errors through the constraint-validation API. A syntax error, for example, sets the "typeMismatch" property to true. This check runs when the user leaves the input, submits the form, or when you call the "reportValidity()" method. Mobile browsers also show an "@"-optimized keyboard.
<form>
<input id="workMail" type="email" required autocomplete="email">
<button>Send</button>
</form>
The Pattern Attribute
You can add another validation layer with the pattern attribute. This attribute lets you specify a regular expression that the input value must match. The browser evaluates this pattern after it performs the built-in syntax check for the email type.
If the value is a syntactically correct email but fails the pattern, the browser flags a "patternMismatch" on the element's validity state. This is useful for specific rules, like a domain whitelist. The regular expression must match the entire input string.
<input id="corpMail"
type="email"
pattern=".+@beststartupever\.com"
title="Use your company address"
required>
JavaScript and the Constraint Validation API
For more control, you can use JavaScript with the Constraint Validation API. The element's "validity" property gives you detailed flags about the input's state, such as "valueMissing" or "typeMismatch". You can create custom validation logic based on these flags.
With the "setCustomValidity" method, you can define your own error messages. For instance, you could suggest a correction for a common typo like ".con" instead of ".com". To display these messages, you call the "reportValidity" method, which shows feedback without a block on the form submission process.
const f = document.querySelector('form');
const mail = f.elements.email;
mail.addEventListener('input', () => {
if (mail.validity.typeMismatch) {
mail.setCustomValidity('Not a valid address');
} else if (mail.value.endsWith('.con')) {
mail.setCustomValidity('Did you mean “.com”?');
} else {
mail.setCustomValidity('');
}
mail.reportValidity();
});
Challenges of HTML Email Validation
While client-side checks offer immediate feedback, they come with significant limitations. These methods often create a false sense of security and can fall short when faced with real-world email address variations.
- The vast RFC syntax for emails means built-in constraints and pattern attributes often fail. They may block valid addresses with unusual formats or permit invalid ones, which creates unreliable results.
- Browser validation engines differ. An address that passes on one browser might fail on another due to inconsistent regex parsers. This makes client-side checks with the pattern attribute or native input nondeterministic.
- Internationalized mail with non-ASCII characters poses a problem. Browser inconsistencies with these formats often cause HTML validation to reject or incorrectly rewrite valid international email addresses, which requires server-side fixes.
- HTML validation only inspects syntax. Methods like the native input, pattern attribute, or JavaScript API cannot confirm if an address is deliverable. A syntactically correct but fake email will pass.
Validate Emails with Abstract API
Validate emails at sign-up to improve data accuracy and ensure your messages reach the inbox.
Get started for free
How Abstract API Handles Email Validation
Abstract API addresses the core weaknesses of traditional methods through a comprehensive, multi-layer check.
- It validates syntax and offers corrections for common typos.
- The system confirms a domain possesses valid MX records and can accept mail.
- An SMTP handshake verifies the actual existence of the mailbox.
- It identifies disposable, role-based, and catch-all email addresses.
- The API returns a deliverability status and a quality score to help you evaluate the address.
How to Add Abstract API to Your Dev Environment
Once you're familiar with Abstract’s capabilities, you add its email validation API to your project with ease.
- Create an Abstract account and copy the Email Validation API key from the dashboard.
- Add the key to your secret store, such as dotenv or AWS Secrets Manager.
- Install an HTTP client like axios or fetch.
- In your form's submit handler, call the API endpoint.
- Parse response fields like deliverability and quality_score to accept, warn, or reject the address.
- Deploy your code. Abstract scales and updates its heuristics automatically.
async function validateEmail(email) {
const url = `https://emailvalidation.abstractapi.com/v1/?api_key=${process.env.ABSTRACT_KEY}&email=${encodeURIComponent(email)}`;
const res = await fetch(url);
if (!res.ok) throw new Error('API error');
return res.json();
}
// form submit
const data = await validateEmail(values.email);
if (data.deliverability !== 'DELIVERABLE' || data.is_disposable_email.value) {
setError('Enter a reachable, non-disposable address.');
} else {
continueSubmit();
}
Sample Email Validation Implementation with Abstract API
The API returns a detailed JSON object. This response provides multiple data points that let you build more robust validation logic than simple HTML checks allow. You can use these flags to enforce stronger rules without the need to run your own SMTP probes or maintain provider blocklists.
{
"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 "deliverability" and "quality_score" fields quantify the risk associated with an email address. The "autocorrect" field suggests a correction for common typos. Flags like "is_disposable_email" and "is_role_email" let you block temporary addresses or group aliases, while "is_mx_found" and "is_smtp_valid" confirm the domain accepts mail and the specific mailbox exists.
Final Thoughts
Traditional validation only checks format. This means you still accept disposable mailboxes, domains without mail servers, and addresses with typos that will bounce. Abstract API performs a multi-layer check to solve these issues.
To reliably validate user emails, create an account on Abstract API and get your free API key.
Validate Emails with Abstract API
Validate user emails at the point of entry to maintain a clean list and improve deliverability.
Get started for free