Article

How to Validate Email in TypeScript: Syntax, MX, and Mailbox Checks

By Unlimited Verifier Team ·

Flow diagram showing a TypeScript email validation pipeline with syntax, MX lookup, and mailbox checks leading to Valid, Invalid, or Risky verdicts.

Summary

To validate an email in TypeScript, run three layers in order: a fast syntax check with validator.js or Zod, a DNS MX lookup on the domain, and a mailbox check over SMTP or a hosted API. Only the mailbox layer confirms that an inbox actually accepts mail, so run the costlier checks only on addresses that pass the cheap ones.

Validate an email in TypeScript in three layers: a syntax check with validator.js or Zod, an MX lookup on the domain, and a mailbox check over SMTP or a hosted API, which is the layer that tests whether the inbox exists. For the broader product context, see our real-time email validation guide.

Quick answer

What does validating an email in TypeScript actually check?

Email validation is a set of checks ordered by cost. Each layer catches a different kind of bad address, and the expensive layers should only run on addresses that pass the cheap ones.

  1. Format: Is the string shaped like an address, with one @, a local part and a domain?
  2. Length: Does it respect the limits in RFC 5321? The local part may be up to 64 octets and the domain up to 255.
  3. Domain routing: Does the domain publish MX records, or an A record that mail can fall back to?
  4. Mailbox: Does the receiving server accept the recipient?
  5. Risk flags: Is the domain disposable, is the local part a role account such as info@, or is the domain catch-all?

The result usually falls into one of three buckets. Valid means the address passed every check. Invalid means it failed a hard check, such as a missing mailbox or no mail route. Risky covers addresses that may be deliverable but are low-value or unconfirmable.

Checks 4 and 5 are policy signals as much as technical ones. A role address such as billing@ is fine for a receipt but a poor target for a cold campaign, so decide per use case rather than deleting every flagged address.

Bottom line: Checks 1 and 2 are local and free. Checks 3 to 5 need DNS or network calls, so run them only on addresses that survive the cheap checks.

Why isn't a regex enough?

A regex can catch obvious typos, but it cannot tell you whether anyone reads the inbox. The address grammar in RFC 5322 is far more permissive than most developers expect. It allows quoted local parts, comments and IP-literal domains. A regex that follows the grammar closely becomes long and hard to audit, and it still accepts user@localhost, which is valid syntax but not a real internet mailbox.

RFC 3696, an informational RFC on checking names in applications, makes the same point: address syntax is harder than it looks. Two practical rules follow:

Bottom line: Use a regex, if at all, as a fast pre-filter. Trust a maintained library for the syntax decision and let DNS and mailbox checks answer the rest.

How do you validate email syntax in TypeScript?

Use a maintained library rather than a homemade pattern. The two common choices do different jobs:

Neither library checks the mailbox. Both answer "is this shaped like an address?" and nothing more.

The module below normalizes input, applies length limits and runs validator.isEmail:

// syntax.ts
import validator from "validator";
import { domainToASCII } from "node:url";

export function normalize(raw: string): string {
  const s = raw.trim();
  const at = s.lastIndexOf("@");
  if (at < 1) return s;
  // Convert internationalized domains to punycode, e.g. bücher.example -> xn--bcher-kva.example
  const domain = domainToASCII(s.slice(at + 1).toLowerCase());
  return `${s.slice(0, at)}@${domain}`;
}

export function isSyntaxValid(email: string): boolean {
  if (email.length > 254) return false;
  const at = email.lastIndexOf("@");
  if (at < 1 || at === email.length - 1) return false;
  if (email.slice(0, at).length > 64) return false;
  return validator.isEmail(email, { require_tld: true });
}

Two details matter in practice. First, lowercase the domain for storage and deduplication, but keep the local part as the user typed it, because RFC 5321 says the local part may be case-sensitive even though most providers treat it case-insensitively. Second, domainToASCII returns an empty string for input it cannot convert, so the address fails the final check instead of slipping through.

Run syntax checks on blur or submit, not on every keystroke, and always repeat them on the server.

Bottom line: Normalize first, then apply length limits and a maintained library. The server should always repeat the check the browser ran.

How do you check that a domain can receive mail?

Use an MX lookup. MX records list the servers that accept mail for a domain. Node's built-in dns/promises module, documented on the Node.js DNS page, does this without an extra package. For a deeper look at MX edge cases, see our MX record lookup guide.

Three cases need care:

Because a list has many addresses per domain, caching matters more than the lookup itself. The module below caches one promise per domain, so concurrent requests share a single lookup:

// domain.ts
import { resolveMx, resolve4 } from "node:dns/promises";

export type Route = "routable" | "no-mail" | "unknown";

const errCode = (err: unknown) => (err as NodeJS.ErrnoException).code;
const cache = new Map<string, Promise<Route>>();

export function mailRoute(domain: string): Promise<Route> {
  const hit = cache.get(domain);
  if (hit) return hit;
  const p = lookup(domain).then((route) => {
    if (route === "unknown") cache.delete(domain); // retry transient failures later
    return route;
  });
  cache.set(domain, p);
  return p;
}

async function lookup(domain: string): Promise<Route> {
  try {
    const mx = await resolveMx(domain);
    const usable = mx.filter((r) => r.exchange !== "." && r.exchange !== ""); // null MX, RFC 7505
    return usable.length > 0 ? "routable" : "no-mail";
  } catch (err) {
    if (errCode(err) === "ENOTFOUND") return "no-mail"; // domain does not exist
    if (errCode(err) !== "ENODATA") return "unknown";   // timeout, server failure
  }
  try {
    await resolve4(domain); // implicit MX: fall back to the A record
    return "routable";
  } catch (err) {
    return errCode(err) === "ENODATA" || errCode(err) === "ENOTFOUND" ? "no-mail" : "unknown";
  }
}

A domain typo such as gmial.com can still have valid MX records, so an MX check will not catch it. Offer a "did you mean" suggestion in the form UI as a separate step.

Bottom line: An MX check removes dead and no-mail domains cheaply, but it says nothing about individual mailboxes. Cache per domain and keep "unknown" separate from "invalid."

How do you check whether a mailbox exists?

A mailbox check opens an SMTP conversation with the domain's mail server and asks whether it would accept a recipient, without sending a message. The sequence is EHLO, MAIL FROM, RCPT TO, then QUIT, closed before any DATA command. The reply to RCPT TO carries the signal:

Reply to RCPT TO What it means Your label
250 Server accepts the recipient Valid, unless the domain is catch-all
252 Server declines to confirm but will attempt delivery Risky
550 with enhanced code 5.1.1 Mailbox does not exist (RFC 3463 enhanced status codes) Invalid
4xx, such as 450 or 451 Temporary failure, often greylisting Retry later; Risky if it persists
Other 5xx, or connection refused Policy block or closed port Unknown; hold as Risky

Running this yourself is harder than it looks. Many cloud providers block outbound port 25 by default, large mailbox providers throttle or refuse repeated probes, and a catch-all server returns 250 for addresses that don't exist. Your sending IP's reputation also affects whether the probe gets a meaningful answer. The guide to why SMTP verification gets blocked covers these failure modes.

For that reason, most teams find it easier to run the mailbox step through a hosted service. The Unlimited Verifier REST API checks syntax, domain, MX and the SMTP mailbox, then sorts results into Valid, Risky or Invalid. Catch-all domains are flagged, and that is the part a hand-built probe is hardest to get right.

Bottom line: A 250 response on a catch-all domain proves nothing about a specific mailbox. Treat catch-all results as Risky and don't count them as confirmed.

Which validation method should you use?

Use the cheapest method that answers your question, and combine methods when you clean a list. The table compares the realistic options.

Method What it catches What it misses Where it runs Limits and cost
Regex only Typos, missing @, spaces Dead domains, missing mailboxes Browser or server No cost; hard to maintain
validator.js or Zod Malformed syntax, single-label domains Everything after syntax Browser or server No cost; syntax only
MX lookup via dns/promises Nonexistent domains, null MX, no-mail domains Mailboxes on live domains Server DNS query volume; cache per domain
Self-run SMTP probe Many nonexistent mailboxes Catch-all ambiguity; blocked ports Server with port 25 open and clean IP reputation You manage IPs, retries and throttling
Hosted verification API (Unlimited Verifier) Syntax, domain, MX, SMTP mailbox, catch-all, disposable and role flags Engagement and consent; a valid mailbox is not an opted-in subscriber Any code that can make HTTPS requests Pro plan includes API access (100,000 emails a month); Free plan has no API access; batches up to 10,000 per request

If you are comparing hosted products, our roundup of the best email verification tools covers how they differ. For TypeScript specifically, the real question is whether you want to operate the SMTP layer yourself.

Once you have verdicts, decide what to do with each one:

Verdict Typical cause Action
Valid Domain routes mail, mailbox accepted, not disposable or role Send first, starting with the most engaged
Risky: catch-all Server accepts any recipient Hold until the end of your ramp
Risky: role or disposable info@, sales@, throwaway domains Suppress for marketing; keep only where a transactional need exists
Invalid No MX, null MX, or nonexistent mailbox Suppress permanently

Bottom line: Syntax and MX checks are cheap and belong in your code. The mailbox check is the expensive layer, and a hosted API is usually the practical way to run it.

How do you validate a large list in TypeScript?

Run the cheap layers first so the expensive ones only see addresses that could work. Dedupe, check syntax, check domains, and only then send the remainder to a mailbox check.

Here is a worked example with illustrative numbers. Imagine a SaaS team's list cleaning job on a 50,000-row export: 42,000 product signups and 8,000 trade-show leads.

  1. Deduplicate. 50,000 rows reduce to 47,800 unique addresses (2,200 duplicates).
  2. Syntax and length. 1,100 addresses fail. 47,800 − 1,100 = 46,700 remain.
  3. Domain pass. The 46,700 addresses sit on 6,400 unique domains. Caching means 6,400 DNS lookups instead of 46,700, which is 40,300 fewer. Of those domains, 380 are no-mail, covering 1,240 addresses. 46,700 − 1,240 = 45,460 candidates.
  4. Mailbox pass. 45,460 ÷ 10,000 = 4.55, so 5 requests: four full batches of 10,000 and one of 5,460.
  5. Quota. On Pro, 100,000 API emails a month. Using 45,460 leaves 54,540 for the rest of the month.
  6. Deep checks. Suppose 4,000 catch-all candidates need deep verification. Against Pro's 25,000 monthly deep verifications, that is 16%.
  7. Storage. The output is a Valid list, a Risky list and an Invalid list, with counts you can report.

Programmatic batching avoids a limit that matters for upload-based cleaning. On Pro, each uploaded list can hold up to 25,000 emails, so a 50,000-row file has to be split into two uploads. The Free plan allows 150 emails per list and has no API access, so it cannot run this pipeline.

Bottom line: Dedupe and domain caching remove most of the expensive work before any mailbox check runs, and the arithmetic shows exactly how much quota the job uses.

How do you validate a CSV in TypeScript, step by step?

This tutorial assumes Node.js 18 or later, a file called list.csv with an email header, and a Pro account with API access for the mailbox step. The no-code path is covered at the end.

  1. Set up the project. Run npm init -y, then add "type": "module" to package.json so top-level await works. Install dependencies with npm install validator csv-parse and npm install -D typescript tsx @types/validator @types/node. Run the script with npx tsx triage.ts.
  2. Add the syntax module. Create syntax.ts with the normalize and isSyntaxValid functions from the syntax section.
  3. Add the domain module. Create domain.ts with the mailRoute function from the MX section.
  4. Parse the CSV properly. Use csv-parse rather than split(","). A quoted field containing a comma will break naive splitting.
  5. Create triage.ts. Replace the verifyBatch body with a POST to your hosted API, using the key from the API keys page. Until you do, the script throws on purpose.
// triage.ts
import { readFileSync, writeFileSync } from "node:fs";
import { parse } from "csv-parse/sync";
import { normalize, isSyntaxValid } from "./syntax";
import { mailRoute } from "./domain";

type Verdict = "valid" | "risky" | "invalid";

// Placeholder: replace the body with a POST to your hosted verification API.
async function verifyBatch(emails: string[]): Promise<{ email: string; verdict: Verdict }[]> {
  throw new Error(`Connect the API first (${emails.length} addresses waiting)`);
}

const chunk = <T>(xs: T[], n: number): T[][] =>
  Array.from({ length: Math.ceil(xs.length / n) }, (_, i) => xs.slice(i * n, i * n + n));
const domainOf = (email: string) => email.slice(email.lastIndexOf("@") + 1);

const rows = parse(readFileSync("list.csv"), { columns: true, skip_empty_lines: true }) as { email: string }[];
const unique = [...new Set(rows.map((r) => normalize(r.email)))];

const verdicts = new Map<string, Verdict>();
const undecided = () => unique.filter((e) => !verdicts.has(e));

// 1. Syntax
for (const e of unique) if (!isSyntaxValid(e)) verdicts.set(e, "invalid");

// 2. Domain routing, 50 domains at a time to avoid flooding the resolver
const dead = new Set<string>();
for (const batch of chunk([...new Set(undecided().map(domainOf))], 50)) {
  const routes = await Promise.all(batch.map(async (d) => [d, await mailRoute(d)] as const));
  for (const [d, route] of routes) if (route === "no-mail") dead.add(d);
}
for (const e of undecided()) if (dead.has(domainOf(e))) verdicts.set(e, "invalid");

// 3. Mailbox pass through the hosted API, 10,000 addresses per request
for (const batch of chunk(undecided(), 10_000)) {
  for (const r of await verifyBatch(batch)) verdicts.set(r.email, r.verdict);
}

// 4. One file per verdict
for (const v of ["valid", "risky", "invalid"] as Verdict[]) {
  const emails = [...verdicts].filter(([, x]) => x === v).map(([e]) => e);
  writeFileSync(`${v}.txt`, emails.join("\n"));
}
  1. Store the results yourself. Save the verdicts to your own database or CSV. Results are kept 30 days on Pro and 24 hours on Free, so an archive you control is the only record you can rely on.
  2. Import only Valid addresses first. Upload valid.txt as a new segment in your sending platform, and suppress the contents of invalid.txt there. Platforms without native integrations need this export-and-re-import step.

If you'd rather skip the code, upload and verify a list as a CSV or Excel file of up to 10MB, with the email column detected automatically. To spot-check a single address before a big run, the free email checker gives a result without any setup. To get started, sign up and choose the plan that fits your volume.

Bottom line: The script stays short because the decisions live in the layers. Store the verdicts and import Valid addresses first.

How much does mailbox verification cost per 1,000 addresses?

The honest answer depends on how much quota you use, because Pro is a flat monthly subscription. Email verification pricing is easiest to compare as an effective rate per 1,000 addresses.

Standard verification has no per-email fee on any plan. Before you schedule a recurring job, confirm how API calls draw down the monthly allowance on the API keys page.

Bottom line: Compare plans by effective cost per 1,000 at the volume you actually run, not by the sticker price.

What mistakes should you avoid?

Bottom line: Most failures come from confusing a format check with a deliverability check, or from storing results nowhere you control.

Where should you validate in a real product?

Validate at every point where addresses enter your system, and apply the same rules everywhere. For signup, the signup form guide covers inline feedback and when to call the API. For React forms, the React Hook Form validation guide shows how to connect schema rules to the UI. If you validate outside React, see how to validate email in JavaScript. For sales lists, the prospecting guide explains why B2B addresses decay quickly.

The same layers apply in other languages. See our guides to Python libraries, Go packages and Spring Boot. Before you parallelize a large job, check API rate limits. For ongoing hygiene and re-verification schedules, see the list maintenance guide.

Bottom line: Validate at entry, re-verify on a schedule, and keep one set of rules across every language and service.

How we compared (and limitations)

This guide is based on public documentation: the RFCs cited above, the Node.js DNS and URL documentation, and the published documentation for validator.js and Zod. We have not benchmarked false-positive or false-negative rates for any library, and we have not run SMTP probes against live mail providers. Library APIs change between versions, so check current documentation before you ship.

Unlimited Verifier's plan details come from its published plan facts. The 99.5% accuracy figure is the company's stated figure for deep verification, not an independent benchmark. All worked-example numbers, including the 50,000-row list and its breakdown, are illustrative.

Three-layer validation pipeline

Layer Check Cost Possible result
1. Syntax validator.js or Zod .email(), length cap of 254 Local, no network Invalid on failure
2. Domain node:dns/promises resolveMx, cached per domain DNS lookup Invalid if no mail route
3. Mailbox SMTP probe or hosted API Network, slowest Valid, Invalid, or Risky (catch-all)

Run layer 2 only on addresses that pass layer 1, and layer 3 only on those that pass layer 2.

Frequently asked questions

What is the best library to validate email in TypeScript?

For syntax checks, validator.js and Zod's .email() schema are the most common choices. Both run in-process with no network call and reject malformed strings. Neither confirms that a mailbox exists, so pair them with a DNS MX lookup and, where accuracy matters, a mailbox check.

How do I check MX records in Node.js?

Use the promise-based resolver in node:dns/promises and call resolveMx with the domain part of the address. A null or empty result suggests the domain has no mail route. Cache results per domain, since many addresses share the same provider and repeated lookups waste time.

Can a regex fully validate an email address?

No. A regex can catch obvious typos but cannot confirm that a mailbox exists or accepts mail. The RFC 5322 grammar is also far more permissive than most patterns allow, so a strict regex may reject valid addresses while still accepting unroutable ones like user@localhost.

What is a catch-all domain and why does it matter?

A catch-all domain accepts mail for any local part, so a positive response does not prove that the specific mailbox exists. Treat these addresses as Risky rather than Valid, and consider holding them until you have seen engagement or bounce data from the rest of your list.

Should I send email to role addresses like info@ or billing@?

Role addresses are usually deliverable but often go to shared inboxes and are poor targets for cold outreach. They are fine for transactional messages such as receipts. Decide per use case instead of deleting every flagged address automatically.

How long should an email address be in TypeScript validation?

RFC 5321 limits the local part to 64 octets and the domain to 255. In practice, many implementations reject any full address over 254 characters before running a regex. Checking length first also protects against slow pattern matching on very long inputs.

Does validating an email send it a message?

Syntax and MX checks do not send mail. A mailbox check typically opens an SMTP session and asks whether the recipient is accepted, usually without delivering a message. Some providers handle this differently, so review each vendor's documentation before relying on it.

How do I validate thousands of emails efficiently in TypeScript?

Run the cheap local checks first, filter out failures, then batch the survivors through a hosted verification API rather than opening thousands of individual SMTP connections. Store each verdict with a timestamp so you do not re-verify addresses unnecessarily.

Is an email that passes syntax validation guaranteed to be deliverable?

No. Syntax validation only confirms the shape of the string. An address can be well formed and still belong to a closed mailbox, a disposable domain, or a domain with no mail server, so later layers are required.

Cut Bounces and Protect Your Sender Reputation With Unlimited Email Verification

Every invalid address you send to hurts your sender reputation and your inbox placement. Verifying your list before each send means fewer bounces, healthier deliverability, and a predictable cost. With Unlimited Verifier, standard verification is unlimited on every plan, with no per-email fees.

Unlimited Verifier checks syntax, domain, MX records and the SMTP mailbox. It also detects catch-all domains and flags disposable and role-based addresses. Export a CSV from your email platform or CRM, upload and verify the list, then re-import the clean results. You can also automate checks with the email verification API.

Free Pro
Price $0 $29/month ($25/month billed annually)
Lists 25 a month, up to 150 emails each Unlimited, up to 25,000 emails each
Deep verifications 750 a month 25,000 a month
API access No Yes (100,000 emails a month)
Result retention 24 hours 30 days

Why teams choose Unlimited Verifier

Unlimited Verifier states 99.5% accuracy for deep verification.

Create a free account and verify your next list before you hit send.

Want to test a single address first? Try the free email checker.