Back to the blog

Tony CantaveHow I Validate Form Input in Plain JavaScript Before It Reaches the Server

By Tony Cantave ·

In delivery and dispatch work, I learned that a missing detail costs almost nothing to fix at the desk and a lot to fix on the road. Web forms work the same way. If someone types a four digit ZIP code or leaves the email field half finished, the best time to tell them is right then, while the form is still on their screen.

I do not reach for a library for this. Plain JavaScript and a few built in browser features cover nearly everything a small site needs. Here is the pattern I use.

Start with honest HTML

The browser already knows a lot about forms, so I describe each field properly first.

<form id="signup" novalidate>
  <label for="name">Your name</label>
  <input id="name" name="name" required maxlength="80">

  <label for="email">Email</label>
  <input id="email" name="email" type="email" required>

  <label for="zip">ZIP code</label>
  <input id="zip" name="zip" inputmode="numeric" required>

  <label for="message">Message</label>
  <textarea id="message" name="message" maxlength="1000"></textarea>

  <p id="errors" role="alert"></p>
  <button type="submit">Send</button>
</form>

Every input has a real label, which helps screen readers and makes the click target bigger. The inputmode attribute brings up a number pad on phones. I add novalidate to the form so the browser does not show its own popups, because I want one consistent set of messages that I control. The paragraph with role="alert" is where errors appear, and assistive technology reads its changes aloud.

Keep the rules in one place

Each field gets a small function that returns true when the value is fine, or a message when it is not.

const rules = {
  name: (value) => value.length >= 2 || "Please enter your name.",
  email: (value) =>
    /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value) || "That email address looks incomplete.",
  zip: (value) => /^\d{5}$/.test(value) || "ZIP code should be five digits.",
  message: (value) =>
    value.length <= 1000 || "Please keep the message under 1000 characters.",
};

Having the rules in one object means I can read every requirement for the form in a few lines, and adding a field is one more entry. The email check is deliberately loose. It confirms there is something before and after the @ sign and a dot in the domain. Trying to fully validate email addresses with a regular expression rejects real addresses and still cannot prove the inbox exists.

One function that checks everything

function validateForm(form) {
  const data = Object.fromEntries(new FormData(form));
  const errors = {};
  for (const [field, check] of Object.entries(rules)) {
    const value = String(data[field] ?? "").trim();
    data[field] = value;
    const result = check(value);
    if (result !== true) errors[field] = result;
  }
  return { data, errors };
}

FormData reads every named field, so I never query inputs one at a time. I trim each value before checking it, because a name made of three spaces should not count as filled in, and I store the trimmed value so that is what gets sent. The function returns both the cleaned data and every error at once, which means the person sees all their problems together instead of fixing one, submitting, and finding the next.

Showing the messages

const form = document.getElementById("signup");
const errorBox = document.getElementById("errors");

form.addEventListener("submit", (event) => {
  event.preventDefault();
  const { data, errors } = validateForm(form);

  for (const field of Object.keys(rules)) {
    form.elements[field].setCustomValidity(errors[field] ?? "");
  }

  const messages = Object.values(errors);
  errorBox.textContent = messages.join(" ");

  if (messages.length === 0) {
    sendForm(data);
  } else {
    form.elements[Object.keys(errors)[0]].focus();
  }
});

setCustomValidity marks a field as invalid or clears it, so CSS using the :invalid selector can highlight the right boxes. Moving focus to the first broken field saves a scroll on a phone. I use textContent rather than innerHTML for the messages, so nothing a person types can ever be turned into markup on the page.

I also check a single field when someone leaves it, which feels responsive without nagging them while they are still typing.

form.addEventListener("focusout", (event) => {
  const check = rules[event.target.name];
  if (!check) return;
  const result = check(event.target.value.trim());
  event.target.setCustomValidity(result === true ? "" : result);
});

Sending it

async function sendForm(data) {
  const response = await fetch("/api/contact", {
    method: "POST",
    body: new URLSearchParams(data),
  });
  errorBox.textContent = response.ok
    ? "Thanks, your message was sent."
    : "Something went wrong on our side. Please try again in a minute.";
}

Passing URLSearchParams as the body lets the browser set the right content type for me.

The server still decides

Everything above is for the person filling out the form. None of it is security. Anyone can turn off JavaScript or send a request straight to the endpoint, so the server repeats the same checks and rejects anything that fails. What I like about keeping the rules small and plain is that porting them to the backend is easy, whether that is Python or Node.

What I took away

Good validation is mostly about kindness: catch the mistake early, say exactly what is wrong, and do not make anyone guess. It takes about fifty lines of JavaScript, and it turns a frustrating form into one people actually finish.