Skip to content

How to validate an email address in JavaScript (and what to check on the server)

· Updated · 7 min read · Tutorials

To validate an email address in JavaScript, use three layers: input type="email" in the browser for instant feedback, a short shape check on the server (never trust the browser), and a server-side API call for what no pattern can know, such as whether the domain receives mail, whether it's a typo of gmail.com, or whether it's a throwaway inbox. A regex alone only tells you the string looks like an email. Below is working code for each layer, browser and Node.

Layer 1: let the browser do the format check

Before writing any JavaScript, use the input type that already validates:

<form id="signup" novalidate>
  <label for="email">Work email</label>
  <input id="email" name="email" type="email" autocomplete="email" required maxlength="254">
  <p id="email-error" role="alert"></p>
  <button type="submit">Sign up</button>
</form>

type="email" gives you the right mobile keyboard, autofill, and a format check against the HTML specification's definition of a valid email address. You can read the result from JavaScript instead of relying on the browser's default bubble:

const form = document.querySelector('#signup');
const input = document.querySelector('#email');
const error = document.querySelector('#email-error');

function showFormatError() {
  if (input.validity.valueMissing) error.textContent = 'Enter your email address.';
  else if (input.validity.typeMismatch) error.textContent = 'That doesn\'t look like an email address.';
  else error.textContent = '';
  return input.validity.valid;
}

input.addEventListener('blur', showFormatError);
form.addEventListener('submit', (e) => {
  if (!showFormatError()) e.preventDefault();
});

What the spec's definition does and doesn't do, so you're not surprised:

  • It's a "willful violation" of RFC 5322, by the spec's own wording: no quoted local parts, no comments, which is what you want for a signup form.
  • It accepts a@b and jane@localhost. A dot in the domain isn't required, because intranet addresses exist.
  • It accepts jane..doe@example.com and .jane@example.com, which most mail providers reject.
  • It rejects non-ASCII characters (jöe@example.com, jane@bücher.de). Some browsers convert an internationalized domain to punycode before checking; behaviour varies, so don't count on it.

The browser check is user experience, not security. A bot posts straight to your endpoint and never runs it.

Layer 2: a shape check you can run anywhere

On the server (and optionally in the browser, if you want consistent messages), a short function beats a 400-character regex. This one rejects the things the HTML definition lets through that you almost certainly don't want, and accepts internationalized addresses:

// email-shape.js
export function isPlausibleEmail(input) {
  const email = String(input).trim();
  if (email.length > 254) return false;

  const at = email.lastIndexOf('@');
  if (at < 1 || at === email.length - 1) return false;
  const local = email.slice(0, at);
  const domain = email.slice(at + 1);

  // Local part: 1-64 chars, no spaces or specials that need quoting, no leading/trailing/double dots.
  if (local.length > 64) return false;
  if (!/^[^\s@"(),:;<>[\]\\]+$/.test(local)) return false;
  if (local.startsWith('.') || local.endsWith('.') || local.includes('..')) return false;

  // Domain: at least two labels, each 1-63 letters/digits/hyphens, no edge hyphens,
  // and a TLD of 2+ letters (or a punycode TLD like xn--p1ai).
  const labels = domain.split('.');
  if (labels.length < 2) return false;
  const labelOk = (l) => /^(?!-)[\p{L}\p{N}-]{1,63}(?<!-)$/u.test(l);
  const tldOk = /^(?:\p{L}{2,}|xn--[a-z0-9-]+)$/iu.test(labels.at(-1));
  return labels.every(labelOk) && tldOk;
}

What it returns:

Input type="email" isPlausibleEmail
jane@gmail.com valid true
jane+tag@sub.example.co.uk valid true
a@b valid false
jane..doe@example.com valid false
jane@example.c valid false
jane@bücher.de invalid true
a b@example.com invalid false
jane@gmial.com valid true

That last row is the point of the next section. Why an email regex is never enough goes through the RFC grammar and why matching it fully is the wrong goal.

What no pattern can tell you

jane@gmial.com is a perfectly shaped address. So is jane@company-that-closed.com, and so is k3xq9vz7@ a throwaway inbox service. To catch those you need facts from outside the string:

  • Does the domain exist and have a mail server? A DNS lookup for MX records (with the A-record fallback from RFC 5321).
  • Is the domain a typo of a big provider? gmial.com, hotmial.com, yahooo.com.
  • Is it a disposable inbox? Thousands of throwaway domains exist; the disposable domains category page lists the ones we track.
  • Does the mailbox exist? Only an SMTP conversation with the receiving server can say, and even that can't be confirmed on catch-all domains.

Browsers can't open SMTP connections, and you shouldn't ship a verification API key to the client. So this layer runs on your server.

Layer 3: check the address on the server with fetch

Node 18+ has fetch built in. Two pingutil calls cover different needs:

  • POST /v1/lookup with skip_enrichment: true returns the domain category (free, disposable, company, educational…), email_signals and a verdict in milliseconds. No mailbox check. Good for inline validation on every keystroke-pause or submit.
  • POST /v1/verify does the full check: syntax, disposable list, DNS/MX, an SMTP RCPT TO probe (no email sent) and a catch-all probe. Returns status (valid, invalid, risky, unknown), reason, score and did_you_mean. Takes longer, since it talks to a mail server.
// validate-email.mjs (Node 18+)
import { isPlausibleEmail } from './email-shape.js';

const KEY = process.env.PINGUTIL_KEY;
const BASE = 'https://pingutil.com';

async function post(path, body, timeoutMs) {
  const res = await fetch(BASE + path, {
    method: 'POST',
    headers: { authorization: `Bearer ${KEY}`, 'content-type': 'application/json' },
    body: JSON.stringify(body),
    signal: AbortSignal.timeout(timeoutMs),
  });
  if (!res.ok) throw new Error(`${path}: HTTP ${res.status}`);
  return res.json();
}

/** Fast: category + spam verdict, no mailbox check. */
export async function quickCheck(email) {
  if (!isPlausibleEmail(email)) return { ok: false, message: 'Enter a valid email address.' };
  try {
    const r = await post('/v1/lookup', { input: email, skip_enrichment: true }, 3_000);
    if (r.verdict.is_spam) {
      return { ok: false, message: 'Please use a permanent email address.', reason: r.verdict.reason };
    }
    return { ok: true, category: r.category, lowTrust: r.verdict.low_trust };
  } catch {
    return { ok: true, category: null }; // fail open: don't block signups on an outage
  }
}

/** Full: does the mailbox exist? Plus typo suggestion. */
export async function fullCheck(email) {
  if (!isPlausibleEmail(email)) return { ok: false, message: 'Enter a valid email address.' };
  try {
    const v = await post('/v1/verify', { email }, 30_000);
    if (v.status === 'invalid') {
      return {
        ok: false,
        message: v.did_you_mean
          ? `Did you mean ${v.did_you_mean}?`
          : 'We couldn\'t deliver to this address. Please check it.',
        suggestion: v.did_you_mean,
        reason: v.reason,
      };
    }
    // risky (catch-all, role address) and unknown (server didn't answer): accept.
    return { ok: true, status: v.status, suggestion: v.did_you_mean };
  } catch {
    return { ok: true, status: null };
  }
}

if (import.meta.url === `file://${process.argv[1]}`) {
  const email = process.argv[2];
  console.log('quick:', await quickCheck(email));
  console.log('full: ', await fullCheck(email));
}
export PINGUTIL_KEY=pk_your_key_here
node validate-email.mjs jane@gmial.com

Then expose one endpoint your form calls. Here with Express (setup steps are also on the Express integration page), but any framework works the same way:

// server.mjs
import express from 'express';
import { fullCheck } from './validate-email.mjs';

const app = express();
app.use(express.json({ limit: '4kb' }));

app.post('/api/validate-email', async (req, res) => {
  const result = await fullCheck(String(req.body?.email ?? ''));
  // Return only what the form needs; never echo raw API responses to the client.
  res.json({ ok: result.ok, message: result.message ?? null, suggestion: result.suggestion ?? null });
});

app.listen(3000);

And in the browser, call it after the format check passes:

input.addEventListener('blur', async () => {
  if (!showFormatError()) return;
  const email = input.value.trim();
  try {
    const res = await fetch('/api/validate-email', {
      method: 'POST',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify({ email }),
    });
    const r = await res.json();
    if (input.value.trim() !== email) return; // user kept typing
    if (!r.ok) error.textContent = r.message;
    else error.textContent = r.suggestion ? `Did you mean ${r.suggestion}?` : '';
  } catch {
    // network error: say nothing, the server re-checks on submit anyway
  }
});

Run the same check again in the submit handler on the server. The blur call is for the user; the submit check is the one that counts. If you're on React, real-time email feedback in a React signup form shows the same pattern as a hook with debouncing.

Which check to run when

Moment Check Why
While typing type="email" validity only Instant, free, no network
On blur Server: shape + /v1/lookup fast mode, or /v1/verify Catches typos and throwaway domains before submit
On submit Server: same checks again, then decide The browser can be bypassed
After signup Confirmation email The only proof the person controls the inbox

Rules that save you from support tickets

  1. Reject only on invalid. Treat risky (catch-all, role addresses) and unknown (the server wouldn't answer) as accepted, and let the confirmation email settle it.
  2. Show did_you_mean as a suggestion the user can accept. Don't change the address for them.
  3. Fail open when the API times out or errors. Blocking real users on someone else's outage is worse than letting one bad address through.
  4. Trim whitespace. Don't lowercase the local part for display or sending; do lowercase the domain.
  5. Keep the API key on the server, always.

For timeouts, retries and caching when you take this to production, see the email verification API integration guide. Request and response fields are documented in the API reference.

Questions people ask

What is the best regex to validate an email in JavaScript?
There isn't a perfect one, and you don't need it. Use the browser's built-in type=email check for instant feedback, a short shape check on the server that rejects obvious junk, and a verification call for anything a pattern can't know, such as whether the domain receives mail.
Does input type=email validate the address?
It checks the shape against the HTML specification's definition of a valid email address, which is deliberately looser than the RFCs. It accepts addresses like a@b with no dot in the domain, and it can't tell whether the domain or mailbox exists.
Can I verify an email address from the browser?
Not safely. A verification API needs a secret key, so call it from your server and return only the result the form needs. The browser should only do the fast format check.