Article
How to Validate Email in JavaScript: Regex, MX Lookup, and Mailbox Checks
By Unlimited Verifier Team ·

Summary
To validate an email in JavaScript, combine three layers: a browser regex for typos, a Node.js DNS MX lookup to confirm the domain accepts mail, and an SMTP RCPT TO probe for the specific mailbox. A regex only checks format, so it cannot confirm that an inbox exists. Hosted verification services can cover the mailbox and risk layers when DIY SMTP checks are blocked or unreliable.To validate an email in JavaScript, run three layers: a syntax regex in the browser, a DNS MX lookup on a Node.js server, and an SMTP RCPT TO probe that checks the specific mailbox. Browser code can catch typos, but it cannot confirm that an inbox exists, so each layer answers a different question. For the full picture of checking addresses at the moment they are entered, see our guide to real-time email validation.
Quick answer
- Browser: A simple regex or
type="email"gives instant typo feedback. It is a format check only. - Server (Node.js): Confirm the domain with MX records, falling back to the implicit A-record rule in RFC 5321. Treat DNS timeouts as "unknown," never "invalid."
- Mailbox: An SMTP
RCPT TOprobe asks the recipient's server about one address. Port 25 is often blocked on cloud hosts, and catch-all domains accept everything, so many teams hand this step to a hosted service. - Large lists: Export a CSV, verify it in bulk, and re-import only the Valid rows. Keep Risky rows out of your first sends.
What does email validation in JavaScript actually check?
Email validation asks four questions, each more expensive to answer than the last: is the string shaped like an address, does the domain accept mail, does the specific mailbox exist, and is the address risky (catch-all, disposable or role-based)?
- Syntax: Is the string shaped like an address?
- Domain: Does the domain exist and accept mail?
- Mailbox: Does the receiving server accept this specific address?
- Risk: Is the address catch-all, disposable or a shared role account?
Many JavaScript tutorials stop at the first question, which is one reason validated lists still bounce. A well-formed address such as jane@acme-widgets.example passes a regex, then fails at delivery if the mailbox was closed years ago.
Before you choose a method, compare best email verification tools by the layers they actually cover. Some stop at syntax; others check the mailbox and flag risk.
| Method | Runs in | What it proves | What it cannot prove | Effort to build |
|---|---|---|---|---|
| Regex | Browser or Node | The string is shaped like an address | The domain or mailbox exists | Minutes |
input type="email" |
Browser | The browser's own syntax rule passes | Domain or mailbox validity | None |
Syntax library (for example, validator.js isEmail()) |
Node | Syntax against configurable options | Deliverability | Low |
| DNS MX/A lookup | Node | The domain is set up to receive mail | Any specific mailbox | Low, but needs careful error handling |
DIY SMTP RCPT TO probe |
Node server | The receiving server accepted the recipient at that moment | Catch-all status, consent, reliability from blocked networks | High |
| Hosted bulk verification | Upload or API | Syntax, domain, MX, SMTP mailbox, catch-all, disposable and role flags, sorted into Valid, Risky or Invalid | Consent or engagement | Low: upload a CSV or call the API |
Bottom line: A regex tells you whether a string looks like an email. Only the mailbox layer tells you whether it can receive mail, and that is where DIY code gets hard.
Which regex should you use to validate an email in JavaScript?
Use a deliberately simple pattern in the browser: /^[^\s@]+@[^\s@]+\.[^\s@]+$/. It rejects whitespace and any extra @, and it requires a dot in the domain. That is enough to catch typos without rejecting real customers.
The full RFC 5322 grammar is complex, and many regexes found online are wrong in at least one edge case. The bigger practical risk is being too strict. Over-strict patterns reject real people:
- Apostrophes and plus-addressing. Addresses like
o'brien@andname+news@are valid. - Long top-level domains. Patterns that cap the TLD at four letters reject newer TLDs.
If you would rather not maintain a pattern, validator.js's isEmail() is a common choice. Options such as require_tld and allow_utf8_local_part let you match your own policy. Compare alternatives in Node.js validation libraries compared.
Your browser check's job is to block garbage, not to make the final call. Leave the strict decisions to the server and the verification layer, where you can explain each rejection.
// Browser-side format check: fast, forgiving, no network calls
const SIMPLE_EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
function checkFormat(raw) {
const email = raw.trim();
if (email.length === 0 || email.length > 254) {
return { ok: false, reason: 'length' };
}
if (!SIMPLE_EMAIL.test(email)) {
return { ok: false, reason: 'format' };
}
const local = email.slice(0, email.lastIndexOf('@'));
if (local.length > 64) {
return { ok: false, reason: 'local-part-too-long' };
}
return { ok: true };
}
Two details matter here. First, the 64-character local-part limit comes from RFC 5321. The 254-character total limit follows from the SMTP path limit of 256 octets, which includes the angle brackets. Older guidance sometimes cites 320 characters. Where sources disagree, we recommend 254, since that is the length SMTP can carry. Second, lowercase addresses for comparison and deduplication, because most providers treat them case-insensitively in practice. RFC 5321 allows case-sensitive local parts, so keep the original string for sending.
Bottom line: Keep the browser regex simple and forgiving. Put the strictness on the server, where you can justify every rejection.
Is the HTML5 type="email" check enough?
No. <input type="email"> applies the browser's own syntax rule, which the WHATWG HTML standard defines and MDN documents. That rule is deliberately looser than RFC 5322. It accepts jane@localhost, for example, which has no dot. It never looks up the domain or the mailbox.
You can still use it for native feedback. Call input.checkValidity() and read input.validity.typeMismatch to decide what to show. Don't treat a passing result as proof that the address works. We cover the trade-offs in our HTML5 email input limitations article. To check a single address against every layer, try our free email checker.
Bottom line: Native email validation is a UX feature, not a deliverability check.
How do you check that an email domain can receive mail?
Look up the domain's MX records with dns.resolveMx(). If none exist, RFC 5321 lets a domain receive mail through its A record, which is called the implicit MX. Check that too before you call the domain invalid.
The lookup has three rules that most examples skip:
- Null MX. RFC 7505 defines a null MX record, which says the domain accepts no mail. Treat it as invalid, even if an A record exists.
- Timeouts are not failures. A timeout or
SERVFAILmeans you don't know. Mark the result "unknown" and retry later, rather than dropping a real customer. - Internationalized domains. Convert them to ASCII before lookup.
new URL('http://' + domain).hostnameturnsbücher.deintoxn--bcher-kva.de.
const { promises: dns } = require('node:dns');
const TRANSIENT = new Set(['ETIMEOUT', 'ESERVFAIL', 'ECONNREFUSED']);
// Returns 'valid', 'invalid' or 'unknown'. Never treat a DNS timeout as invalid.
async function domainStatus(domain) {
try {
const mx = await dns.resolveMx(domain);
const nullMx = mx.length === 1 && (mx[0].exchange === '' || mx[0].exchange === '.');
if (nullMx) return 'invalid'; // null MX, RFC 7505: accepts no mail
if (mx.length > 0) return 'valid';
} catch (err) {
if (TRANSIENT.has(err.code)) return 'unknown';
// ENOTFOUND or ENODATA: no MX records, so check the implicit MX below
}
try {
const a = await dns.resolve4(domain); // implicit MX, RFC 5321 section 5.1
return a.length > 0 ? 'valid' : 'invalid';
} catch (err) {
return TRANSIENT.has(err.code) ? 'unknown' : 'invalid';
}
}
Two habits pay off quickly. First, cache results per domain for the length of a batch. Lists tend to concentrate on a small set of providers, so the same lookups repeat thousands of times. Second, suggest corrections instead of rejecting. If someone types gmial.com, compare it against the domains you see most often and offer "Did you mean gmail.com?" for near-misses. A suggestion keeps a real signup; a rejection loses it. For a dedicated MX-lookup walkthrough, see how to check MX records programmatically.
Bottom line: DNS tells you the domain can receive mail. It cannot tell you whether a particular mailbox exists.
Can JavaScript confirm that a mailbox exists?
Not in the browser. From a Node.js server, the most direct signal is an SMTP probe. You connect to the recipient's mail server, ask whether it would accept mail for an address, and disconnect before any message content is sent. The sequence is:
- Resolve the domain's MX records and use the host with the lowest preference number.
- Open a TCP connection to port 25 with a short timeout.
- Wait for the
220greeting, then sendEHLOwith a hostname you control. - Send
MAIL FROM:with a sender address on a domain you control. Your sending IP should have matching reverse DNS. - Send
RCPT TO:<address>and read the reply code. - Send
RSET, thenQUIT. Never sendDATA, because that would deliver a message.
The reply code drives the decision. Enhanced status codes such as 5.1.1 come from RFC 3463.
| Reply | Meaning | How to treat it |
|---|---|---|
250 |
Recipient accepted | Likely Valid, unless the domain is catch-all |
550 5.1.1 |
Mailbox does not exist | Invalid |
553 |
Mailbox name not allowed | Usually Invalid, often a malformed local part |
552 |
Storage allocation exceeded | Risky: the address exists but cannot take mail right now |
421, 450, 451 |
Temporary failure or greylisting | Unknown: retry later |
554 or no usable reply |
Policy rejection or blocked connection | Unknown: never mark Invalid on this alone |
Be careful here. Major cloud providers commonly restrict outbound port 25, so a probe from a typical virtual machine can fail for every address. That looks like a list disaster, but it is a networking problem. Receiving servers may also throttle or greylist repeated probes. We explain the causes in why SMTP verification gets blocked.
Bottom line: An SMTP probe is real evidence, but a DIY probe is hard to run reliably at scale. Expect to spend more effort on infrastructure than on the validation logic.
How do you detect catch-all domains and disposable addresses?
Probe the domain with a random address that almost certainly doesn't exist, such as zq7k-probe-8831@<target-domain>. If the server accepts it, the domain is catch-all: it accepts mail for any local part. Every address on that domain will look valid, so none of them can be confirmed individually. Mark them Risky, not Valid. Our catch-all email verification page explains how these results are handled.
Disposable addresses come from throwaway-mail services. Match the domain against a maintained disposable-domain list. These addresses often pass every technical check but are rarely worth keeping.
Role addresses such as info@, sales@, support@ and noreply@ usually belong to a company rather than a person. They can be deliverable, but they matter for personal outreach and consent-based marketing. If you run outbound prospecting, see email verification for sales prospecting.
Don't auto-delete Risky addresses. Segment them. A catch-all domain might belong to a legitimate customer's corporate mail server, so holding those addresses back is safer than rejecting them outright.
Bottom line: Catch-all and disposable checks don't prove an address is bad. They tell you how much confidence a result deserves.
Should validation run in the browser or on the server?
Both, for different jobs. The browser gives instant feedback without a network call. The server is the source of truth, because client-side code can be bypassed. For the architectural trade-offs, see our client-side versus server-side email validation comparison.
A production signup flow looks like this:
- Browser regex on blur. Instant, with no network call, and it catches typos.
- Server re-runs
checkFormatanddomainStatuson submit. Never trust the client alone. - Mailbox check in the background. Call a hosted email verification API so the user doesn't wait on SMTP. Plan the call volume against API rate limits.
- Decide by bucket. Reject Invalid, accept Valid, and flag Risky with a soft message or a confirmation step.
- Confirmation email as the final test. It is the only check that proves the person controls the inbox and wants your mail. That makes it central to email verification compliance and hygiene.
Flag Risky addresses rather than blocking them. Catch-all corporate domains are a common source of real B2B customers, and rejecting them costs signups. For form-level implementation, see how to add real-time email verification to signup forms. Teams running email verification for ecommerce and SaaS usually apply the same pattern at checkout and trial sign-up.
Bottom line: Use the browser for speed, the server for the decision, background verification for certainty, and a confirmation email to close the loop.
How do you validate a large list instead of single addresses?
Use hosted bulk verification for lists of thousands of rows, and keep your own code for the signup path. Scripting a mailbox check across tens of thousands of rows means managing timeouts, retries, per-domain throttling, catch-all detection and result storage.
Unlimited Verifier accepts CSV or Excel files up to 10MB, detects the email column automatically, and checks syntax, domain, MX records and the SMTP mailbox. It flags catch-all, disposable and role-based addresses and sorts every row into Valid, Risky or Invalid. Results export as CSV, Excel or JSON. The verification engine is also open source on GitHub at unlimitedverifier/free-email-verifier, so you can read how each check is implemented.
There are no native ESP, CRM or Zapier integrations. The workflow is export, verify, and re-import, or call the API from your own scripts. For programmatic use, see our overview of email verification API and automation. The step-by-step CSV process is below.
Bottom line: Let a bulk verifier handle the list, and keep the in-code checks for the points where users type addresses.
How do you verify a CSV list step by step?
Export, verify, keep the Valid rows, and suppress the rest. The steps below work for any list in a CSV or Excel file.
- Export your contacts from your CRM or ESP as a CSV with the email column. Keep bounce and unsubscribe files separately.
- Create an account. You can sign up for free. The Free plan has no API access.
- Upload the file on the Upload and verify a list page. CSV and Excel files up to 10MB are accepted, and the email column is detected automatically.
- Run verification and wait for the job to finish.
- Read the three buckets: Valid, Risky and Invalid.
- Export the results as CSV, Excel or JSON straight away. Free keeps results for 24 hours and Pro for 30 days, so download before they expire.
- Re-import Valid contacts into your ESP or CRM, and suppress the Invalid ones. Hold Risky contacts for later segmentation.
Before you spend quota, run your local checkFormat over the file. It removes malformed rows for free, so you don't pay to check strings that can never be valid. Parse the file with a real CSV library, such as the csv-parse package, because a naive split(',') breaks on quoted fields. The loop below shows the full pattern for a plain list with one address per line:
const { readFileSync } = require('node:fs');
const cache = new Map();
function cachedDomainStatus(domain) {
if (!cache.has(domain)) cache.set(domain, domainStatus(domain));
return cache.get(domain);
}
const emails = readFileSync('contacts.txt', 'utf8')
.split('\n').map(s => s.trim()).filter(Boolean);
(async () => {
for (const email of emails) {
const fmt = checkFormat(email);
if (!fmt.ok) { console.log(email, 'invalid', fmt.reason); continue; }
const domain = email.slice(email.lastIndexOf('@') + 1).toLowerCase();
console.log(email, await cachedDomainStatus(domain));
}
})();
This runs sequentially, which is fine for a few hundred addresses. For larger runs, add a concurrency limit per domain. For a repeatable schedule after the first clean, follow our email list maintenance best practices.
Bottom line: Pre-screen locally for free, send the remaining rows through bulk verification, and work only from the three buckets.
What does a 40,000-address validation cost?
A one-off clean of 40,000 rows fits in one Pro month at $29, split into two lists of up to 25,000. The cost depends on how often you verify, so it helps to see each route. The numbers below use Unlimited Verifier's published plan limits. The result percentages are hypothetical.
Route 1: Free plan. The Free plan allows 25 lists a month of up to 150 emails each:
25 × 150 = 3,750 addresses per month
A 40,000-row list is far beyond that, so Free suits samples, not full cleans.
Route 2: Pro plan, CSV upload. Pro allows lists of up to 25,000 emails each:
25,000 + 15,000 = 40,000 (2 lists)
Standard verification is unlimited on every plan, so there is no per-email fee. Pro includes 25,000 deep verifications a month. Use them on the rows you want a second look at.
Hypothetical results:
| Bucket | Count | Share of 40,000 |
|---|---|---|
| Valid | 31,200 | 78% |
| Risky | 5,600 | 14% |
| Invalid | 3,200 | 8% |
Check the sum: 31,200 + 5,600 + 3,200 = 40,000.
Cost. Pro is $29 a month, or $25 a month billed annually. For a single run:
$29 ÷ 40,000 = $0.000725 per address, or $0.725 per 1,000
The annual plan comes to $300 a year, which suits teams that clean lists every month.
Route 3: API, for ongoing signups. API access is a Pro feature and includes 100,000 emails a month. Suppose the same team also gets 3,000 signups a month and re-checks the 40,000-row list through the API in batches of up to 10,000 per request:
4 batch requests × 10,000 = 40,000 emails 40,000 + 3,000 signups = 43,000 of 100,000 used 100,000 − 43,000 = 57,000 emails of headroom
When you compare email verification pricing, focus on the cost per clean, verified address and on whether your usage fits the plan's limits. The sticker price matters less than that.
Bottom line: For a one-off 40,000-row clean, Pro's two-list split costs one month. For ongoing signup checks, the API allowance matters more than list size.
What mistakes do teams make with JavaScript email validation?
- Rejecting valid addresses. Over-strict regexes block apostrophes, plus-addressing and newer TLDs. Let the server handle the edge cases.
- Treating a DNS timeout as Invalid. A timeout means you don't know. Retry it.
- Concluding the list is bad because port 25 is blocked. That is a network failure, not a list problem.
- Sending
DATAduring a probe. That delivers a real message. Stop afterRCPT TOand disconnect. - Probing one server too hard. Rapid-fire
RCPT TOrequests look like abuse. Throttle per domain and per IP. - Blocking Risky addresses outright. Catch-all corporate domains include real customers. Flag them instead.
- Running DNS or SMTP checks on every keystroke. Validate on blur or submit, and cache results per domain.
- Trusting client-side checks alone. Users and bots can bypass browser code.
- Confusing deliverable with consented. A valid address is not an opted-in address. Check consent records separately.
- Skipping the local pre-screen. Malformed rows waste paid quota.
Bottom line: Most failures come from confusing syntax with deliverability, or from treating an uncertain result as a definite one.
How we compared (and limitations)
This article is based on public documentation: RFC 5321, RFC 5322, RFC 3463, RFC 7505, RFC 2606, the WHATWG HTML standard, MDN's documentation of input type="email", and the Node.js dns module documentation. We have not run controlled benchmarks against any mail provider, and mail server behaviour changes without notice.
Where sources disagree, we say so. Maximum address length appears as both 254 and 320 characters. We recommend 254, because that is what the SMTP path limit allows once the angle brackets are counted. Unlimited Verifier states 99.5% accuracy for deep verification. That is the company's own figure, not an independent benchmark. The worked-example percentages are illustrative. Plan limits come from the product's published terms and may change, so check the current pricing before you budget.
Bottom line: Treat browser checks as format screens, DNS as domain confirmation, SMTP as a mailbox signal that needs careful handling, and bulk verification as the dependable route for large lists.
Three-layer validation flow
| Layer | Where it runs | Question answered | Result on failure |
|---|---|---|---|
| 1. Syntax | Browser, then server | Is it shaped like an address? | Show typo message, block submit |
| 2. Domain | Node.js server | Does the domain have MX (or A) records? | Mark Invalid; on timeout, mark Unknown |
| 3. Mailbox | Node.js or hosted API | Does the server accept RCPT TO? | Mark Invalid, Risky (catch-all), or Valid |
Frequently asked questions
Is a regex enough to validate an email in JavaScript?
No. A regex only checks that the string looks like an email address. It cannot confirm that the domain accepts mail or that the specific mailbox exists. Use it for instant typo feedback, then add server-side DNS and mailbox checks for deliverability.
What is the best regex for email validation in JavaScript?
A simple pattern such as /^[^\s@]+@[^\s@]+\.[^\s@]+$/ works well for browser feedback. It rejects whitespace and extra @ symbols and requires a dot in the domain. Avoid overly complex RFC-complete patterns, since they reject valid addresses and add little real-world value.
How do I check if an email domain has MX records in Node.js?
Use the built-in dns module and call dns.promises.resolveMx with the domain part of the address. If records return, the domain is set up to receive mail. Treat timeouts or temporary errors as unknown rather than invalid, and fall back to an A-record lookup only where appropriate.
Does an SMTP RCPT TO check confirm a mailbox exists?
It shows whether the receiving server accepted the recipient at that moment, which is strong evidence but not proof. Catch-all domains accept any address, and some servers hide results. Many providers also block port 25 on cloud hosts, so the check can fail from your network.
Why is port 25 a problem for email validation?
SMTP uses port 25 for server-to-server mail, and many cloud providers block outbound connections on it to limit spam. An SMTP mailbox probe run from those hosts will time out. Teams often run the probe from an unblocked network or use a hosted verification service instead.
What is a catch-all email address?
A catch-all domain accepts mail for any address at that domain, real or not, so an SMTP check cannot confirm a specific mailbox. Verification tools flag these as Risky. Keep them out of first sends and monitor engagement before treating them as deliverable.
Should I validate email on the client or the server?
Do both. Client-side checks give instant feedback and reduce obvious typos. Server-side checks are the only place to run DNS and SMTP tests reliably, and they should never be bypassed because client code can be changed by users.
How do I validate a large email list in JavaScript?
Export the list as a CSV, process it with a bulk verification service or a Node.js script that handles rate limits, and re-import only rows marked Valid. Keep Risky rows out of your first campaign and recheck stale addresses periodically.
Does input type="email" validate the email address?
It applies the browser's basic syntax rule and blocks some malformed input on form submit. It does not check the domain or mailbox, and its exact rules vary by browser, so it should be paired with server-side checks.
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 standard verification on all plans, including Free, with no per-email fees.
- Catch-all detection so you know which domains accept every address.
- Clear Valid / Risky / Invalid results, exportable as CSV, Excel or JSON.
- An open-source verification engine you can inspect on GitHub.
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.