Validate an email address in JavaScript, properly
Most "email validation" is a regex. That catches foo@ but not [email protected], [email protected], or [email protected].
Layer 1: shape (client side)
const ok = /^[^@\s]+@[^@\s]+\.[^@\s]{2,}$/.test(email);
Keep it loose. Strict regexes reject valid addresses such as [email protected].
Layer 2: the domain can receive mail
Look up MX records for the domain. No MX and no A record means mail cannot be delivered. Browsers cannot do DNS directly, so do it on your server, or call an API:
const v = await (await fetch("https://pw-d20261007a2.plainwork-apps.workers.dev/check?email=" + encodeURIComponent(email))).json();
console.log(v.verdict, v.score, v.did_you_mean);
Node.js: check the domain yourself with dns.promises
If you would rather not call an API, Node can do the domain check on your server with the built-in node:dns/promises module. This version returns false for bad shape and for domains with neither MX nor A records (RFC 5321 lets a domain with no MX fall back to its A record):
import { resolveMx, resolve4 } from "node:dns/promises";
export async function checkEmail(email) {
if (!/^[^@\s]+@[^@\s]+\.[^@\s]{2,}$/.test(email)) return { ok: false, reason: "bad-shape" };
const domain = email.split("@").pop().toLowerCase();
try {
const mx = await resolveMx(domain);
if (mx.length) return { ok: true, via: "mx" };
} catch {}
try {
const a = await resolve4(domain);
if (a.length) return { ok: true, via: "a-record" };
} catch {}
return { ok: false, reason: "no-mail-server" };
}
Run against foo@ it returns bad-shape, and against a domain that does not exist it returns no-mail-server. Two limits to know: DNS resolvers in some sandboxes and corporate networks return no MX data even for real domains (then you fall through to the A-record check), and this tells you the domain can receive mail, not that the mailbox exists. It also does not know about throwaway domains: for that, use the disposable domain list or the API above.
Common questions
Which regex should I use for email? A loose one, as in layer 1. The full RFC 5322 grammar is not worth the bugs, and the confirmation email is the real test.
How do I check a valid email format in Node.js? Apply the layer 1 regex first, then checkEmail above on the server.
Layer 3: confirmation email
The only proof an inbox exists and belongs to the user is a confirmation link. Layers 1 and 2 reduce bounces before you send it.
Try the endpoint free (20 per day, no signup) on the main page.
Cleaning an existing list first? Try the free email list cleaner.
Not sure whether a regex is enough? See email regex vs MX check.