Skip to content
MailVet
JavaScript guide

Email validation in JavaScript

In the browser, start with an email input and a short, loose regex: they catch malformed addresses instantly, with no network call. Neither can tell whether the mailbox exists, so run that check on your server, where the API key stays private, and never let it hold up the form.

What JavaScript validation can and can't do

Client-side validation is about the person typing. It catches the slips that happen on every form, such as a missing @, a trailing space or a comma instead of a dot, and it can suggest a fix for a misspelled provider before the form is sent. It costs nothing and feels instant.

What it can't see is the network. A perfectly formatted address can still belong to a mailbox that doesn't exist, a catch-all domain that accepts anything, a disposable inbox that disappears tomorrow, or be a typo at a real domain: jhon@ instead of john@ passes every regex. Those need a verification request, and it has to come from your server, because an API key in browser code is public.

Start with type="email"

The email input type gives you format checking, the email keyboard on phones, and autofill. Its rule comes from the HTML standard and is looser than many expect: it doesn't require a dot in the domain, so dana@localhost passes. novalidate switches off the browser's own error bubbles so you can show your own messages; the validity checks still run.

HTML
<form id="signup" novalidate>
  <label for="email">Work email</label>
  <input id="email" name="email" type="email" autocomplete="email" required>
  <p id="email-hint" aria-live="polite"></p>
  <p id="email-error" role="alert" hidden></p>
  <button type="submit">Create account</button>
</form>

A pragmatic regex and a typo hint

This accepts anything shaped like name@domain.tld and rejects the common mistakes. Don't try to encode RFC 5322 in a regex: it allows quoted strings and comments nobody types into a form. Suggest corrections for misspelled providers, but never change the address silently.

JavaScript
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;

// Common misspellings of big consumer domains. Suggest, don't auto-correct.
const TYPOS = new Map([
  ["gmial.com", "gmail.com"],
  ["gamil.com", "gmail.com"],
  ["gmail.con", "gmail.com"],
  ["hotmial.com", "hotmail.com"],
  ["outlok.com", "outlook.com"],
  ["yaho.com", "yahoo.com"],
]);

function checkEmailFormat(value) {
  const email = value.trim();
  if (email.length > 254 || !EMAIL_RE.test(email)) {
    return { ok: false, message: "Enter an email address like name@company.com." };
  }
  const at = email.lastIndexOf("@");
  const fix = TYPOS.get(email.slice(at + 1).toLowerCase());
  return { ok: true, email, suggestion: fix ? email.slice(0, at + 1) + fix : null };
}

const input = document.getElementById("email");
const hint = document.getElementById("email-hint");

input.addEventListener("blur", () => {
  const { suggestion } = checkEmailFormat(input.value);
  hint.textContent = suggestion ? "Did you mean " + suggestion + "?" : "";
});

Ask your backend, with a time limit

On submit, run the format check again, then ask your own endpoint to verify the mailbox. AbortSignal.timeout() caps the wait. If the check is slow or fails, let the signup through: a real person stuck on a spinner costs more than one unverified address.

JavaScript (browser)
const form = document.getElementById("signup");
const error = document.getElementById("email-error");

async function verifyOnServer(email) {
  try {
    const res = await fetch("/api/check-email", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ email }),
      signal: AbortSignal.timeout(8000),
    });
    return res.ok ? await res.json() : { verdict: "accept" };
  } catch {
    return { verdict: "accept" }; // timed out or offline: don't block a real person
  }
}

function showError(message) {
  error.textContent = message;
  error.hidden = false;
}

form.addEventListener("submit", async (event) => {
  event.preventDefault();
  error.hidden = true;

  const format = checkEmailFormat(input.value);
  if (!format.ok || input.validity.typeMismatch) {
    return showError(format.message ?? "Enter a valid email address.");
  }

  const check = await verifyOnServer(format.email);
  if (check.verdict === "reject") {
    return showError(check.message);
  }
  form.submit();
});

The backend endpoint that calls MailVet

This runs on your server, so the key never reaches the browser. timeout=5 tells the API to answer within five seconds, with pending if a slow catch-all check needs longer. Reject only results that are definitely bad; accept unknown and pending, and pick up the final result from the verification.completed webhook, described in /docs/webhooks.

JavaScript (Next.js route handler)
// app/api/check-email/route.js
const REJECT = {
  invalid_syntax: "Enter a valid email address.",
  invalid_domain: "That domain doesn't receive email. Check for typos.",
  mailbox_not_found: "This address can't receive email. Check for typos.",
  catch_all_no_mailbox: "This address can't receive email. Check for typos.",
  disposable: "Please use a permanent address, not a temporary inbox.",
};

export async function POST(request) {
  const { email } = await request.json().catch(() => ({}));
  if (typeof email !== "string") {
    return Response.json({ verdict: "reject", message: REJECT.invalid_syntax });
  }

  const url = new URL("https://api.mailvet.app/v1/verify");
  url.searchParams.set("email", email);
  url.searchParams.set("timeout", "5");

  let v;
  try {
    const res = await fetch(url, {
      headers: { Authorization: "Bearer " + process.env.MAILVET_KEY },
      signal: AbortSignal.timeout(7000),
    });
    if (!res.ok) throw new Error("MailVet HTTP " + res.status); // 401, 402, 429, 5xx
    v = await res.json(); // 200 with a result, or 202 pending
  } catch (err) {
    console.error("email check skipped:", err);
    return Response.json({ verdict: "accept" });
  }

  if (v.status === "done" && Object.hasOwn(REJECT, v.reason)) {
    return Response.json({ verdict: "reject", message: REJECT[v.reason] });
  }
  // deliverable, risky mailbox_full, unknown or pending: let the signup through
  return Response.json({ verdict: "accept" });
}

Rules that keep the form fast

  • ✓Check the format on blur and again on submit, in the browser
  • ✓Call MailVet from your server, with timeout=5 and a client timeout a little longer
  • ✓Accept unknown and pending: they're uncertain, not bad
  • ✓Show a typo suggestion instead of a hard error when the domain looks misspelled
  • ✓Use a test key (mv_test_…) in development so tests never spend credits
  • ×Putting your API key in front-end code, where anyone can copy it
  • ×Blocking the signup when the check times out
  • ×Rejecting role or free-provider addresses by default on a consumer product
  • ×Treating a passing regex as proof that the address works
FAQ

JavaScript email validation questions

What is the best regex for email validation in JavaScript?

A deliberately loose one: one @, no spaces and a dot in the domain, such as /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/. Longer patterns that try to be strict are hard to maintain and often reject real addresses. Pair the loose regex with a verification check on the server.

Is input type=email enough to validate an email?

It's a good first check for format, and it gives users the right keyboard and autofill. It doesn't require a dot in the domain, anyone can bypass it by editing the page, and it says nothing about whether the mailbox exists. Always check again on the server.

Can I verify an email address in JavaScript without a backend?

Not safely. Checking the mailbox needs an API key, and any key in browser code can be copied and used by anyone. Call the verification API from your own server or a serverless function, and have the browser call that.

Should a signup form wait for email verification?

Only briefly. Most checks finish in a few seconds; cap the wait at around five, and if it runs out, accept the signup and pick up the result later by webhook. Block only addresses that are definitely undeliverable or disposable.

Add a real mailbox check to your form

One request from your backend, a result in seconds, unknowns free. 100 free credits to start.