Skip to content

Form validation

Checking what someone typed against the rules a form needs, telling them what to fix beside the field, and letting the server make the decision that counts. A strong answer covers timing, wording and that second check.

On this page

What it is

Form validation is checking the data in a form against the rules the application needs (a field is required, a value has a format, a number sits in a range) and telling the person what to change. The browser's check is client-side validation; the server's is server-side. On the client there are two kinds: HTML attributes that declare the constraints, and JavaScript that customizes or extends them. HTML validation runs without script and is faster, but less adjustable, so the usual advice is to declare what you can in HTML and add JavaScript where the experience needs it.

The built-in constraints come from the input type and a handful of attributes. type="email" requires a non-empty value to be a syntactically valid address and fails with typeMismatch (an empty field passes unless required is also set); required fails with valueMissing; minlength and maxlength with tooShort and tooLong; pattern, a regular expression the whole value has to match, with patternMismatch; min, max and step bound numbers and dates. These flags live on the element's validity object, so script can tell which rule failed. When someone submits with an invalid field, the browser blocks the submission and shows a message, and that text differs between browsers and follows the browser's language.

Two CSS pseudo-classes mark the state. :invalid matches as soon as a field fails a constraint, which includes an empty required field on a form nobody has touched yet, so a page styled with it opens with red borders. :user-invalid matches an invalid field after the person has interacted with it, or between a submit attempt and their next edit, and has been available across browsers since November 2023. :valid and :user-valid are the mirror images.

To replace the browser's wording, call setCustomValidity() with your text inside the element's invalid event; the Constraint Validation API then shows your message instead of the default. While a custom message is set the field counts as invalid, so pass an empty string to clear it once the value is acceptable. A further step is to suppress the browser's bubble and render the message yourself, next to the field, which is what the sketch below does.

ts
type Field = HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement;
const form = document.querySelector<HTMLFormElement>('#signup')!;
form.noValidate = true; // we render messages ourselves; the constraints still compute
const isField = (el: unknown): el is Field =>
  el instanceof HTMLInputElement || el instanceof HTMLSelectElement || el instanceof HTMLTextAreaElement;

function messageFor(field: Field): string {
  const v = field.validity;
  if (v.valueMissing) return 'Enter your ' + (field.labels?.[0]?.textContent ?? 'value') + '.';
  if (v.typeMismatch && field.type === 'email') return 'Enter an email like name@example.com.';
  if (v.tooShort && 'minLength' in field) return `Use at least ${field.minLength} characters.`;
  if (v.patternMismatch) return field.dataset.hint ?? 'Check the format.';
  return field.validationMessage; // whatever the browser would have said
}

function render(field: Field, msg = field.validity.valid ? '' : messageFor(field)) {
  const box = document.getElementById(field.getAttribute('aria-describedby') ?? '');
  if (box) box.textContent = msg;
  field.setAttribute('aria-invalid', msg ? 'true' : 'false');
}

// leaving a field: the first time we show a judgment
form.addEventListener('focusout', (e) => { if (isField(e.target)) render(e.target); });
// already showing an error: re-check on each keystroke so it clears as they fix it
form.addEventListener('input', (e) => {
  if (isField(e.target) && e.target.getAttribute('aria-invalid') === 'true') render(e.target);
});

form.addEventListener('submit', async (e) => {
  e.preventDefault();
  const fields = [...form.elements].filter(isField);
  fields.forEach((f) => render(f));
  const first = fields.find((f) => !f.validity.valid);
  if (first) return first.focus();
  const res = await fetch(form.action, { method: 'POST', body: new FormData(form) });
  if (res.ok) return; // success handling goes here
  const { errors } = (await res.json()) as { errors: { field: string; message: string }[] };
  for (const err of errors) render(fields.find((f) => f.name === err.field)!, err.message); // same slots
  fields.find((f) => f.getAttribute('aria-invalid') === 'true')?.focus();
});

When to use it

Validate a text field when the person leaves it: listen for blur and check the value at that moment, so a half-typed email isn't called wrong. Our addition: once a field is showing an error, re-check it on each keystroke, because the useful moment is when the error disappears. On submit, check all the fields, show all the messages at once, and move focus to the first invalid one. Keyboard and screen reader users then land on the thing to fix rather than at the bottom of the form.

Write messages that say what would be accepted, not just that the value failed. Tell people the rule before they fail it: put the requirement in text connected to the input with aria-describedby. Signal an error with text or an icon as well as color, since a red and a green border look alike to someone with red-green color blindness. If you keep the browser's bubble, use setCustomValidity() so the wording matches across browsers and languages.

Treat the client check as feedback and the server check as the rule. Invalid data still reaches the server when someone edits the HTML in developer tools, hand-crafts the request, or sets a field's value from script, since some constraints run for typed input and not for values set programmatically. The server validates again with rules consistent with the client's; OWASP lists client-only checks among the common pitfalls and keeps the browser's role to immediate feedback. A good API returns field-level errors so the UI can place them next to the inputs, the same way as the local ones.

Cover semantics, not just syntax. A booking needs two valid dates and an end date after the start; that cross-field rule is one HTML attributes can't express, so it lives in your script on the client and again on the server. Prefer an allowlist (what the field accepts) to a denylist of bad strings. For a regular expression, match the entire value, bound the length before matching, and avoid patterns that backtrack heavily. For email, format checking doesn't prove the mailbox exists, so a verification message is the real check.

Some rules need the server mid-form, such as whether a username is taken. Run that check when the person leaves the field, debounce it if you run it while they type, and cancel or ignore an older response when a newer one is in flight; Debounce and request cancellation covers the mechanics. Show a pending state in the message slot rather than blocking the field.

When not to

Don't flag a field while someone is still typing into it for the first time. A :invalid style or a keystroke listener on a fresh field reports an error for a value that isn't finished, which is why :user-invalid waits for interaction or a submit attempt. The exception is a field that already shows an error: there, re-checking on input is what lets the message go away.

Don't over-constrain. Blocking apostrophes rejects real names and doesn't make a database query safe; a free-text field can accept broad Unicode with a length limit. Don't add a pattern to type="email" just to re-check the address syntax: the type already does that, and the standard accepts forms like user@host without a dot, so a home-made regex rejects valid input. A pattern on an email field is for an application rule on top, such as requiring a particular domain.

Don't build a script validation layer for a short form that doesn't need custom wording. The HTML attributes and the browser's own messages block an invalid submit without any JavaScript, and that is a complete answer for a two-field login or a newsletter box. Add script when the design calls for inline messages, consistent text, or rules the attributes can't express.

Compared

ApproachWhat it doesReach for it whenWhat it costs

HTML attributes, browser messages

required, type, pattern block submit; the browser shows its own text

A short form with no need for custom wording

Message text varies by browser and language; :invalid styles fire before interaction

Attributes plus the Constraint Validation API

Same rules; script reads validity and sets or renders the message

You need inline messages or consistent wording

You own focus, clearing and placement

Script rules beyond the attributes

Cross-field checks such as an end date after a start date

A rule HTML can't express

A second rule set to keep in step with the server

Server check

Rejects what the client missed or skipped and returns field errors

All forms; on its own, for a low-traffic internal tool where a round trip is fine

Errors arrive after submit, one round trip per attempt

Check on each keystroke

Judges the value as it is typed

A field that already shows an error, so it clears as they fix it

Flags a half-typed value on a fresh field

Check when leaving the field

Judges the value once the person moves on

The default for text inputs

A skipped field says nothing until submit

Check on submit

Judges everything at once and focuses the first error

Two or three fields, or a confirm step

Errors arrive late and all together

In a picture

blurTypes in a fieldValid?

Step 1 of 4

Typing is quiet

Someone types into the email field. The attributes required and type="email" describe the rule, and the browser tracks the field's validity as the value changes; our UI shows nothing about it until they leave the field.

How to say it in an interview

The common mistake

Quiz

A sign-up form opens with its required email field already outlined in red. What most likely caused it, and what fixes it?
The form marks the name field required, yet the database contains rows with empty names. How can that happen?
Users on different browsers report different error text for the same empty field. What gives everyone the same message?
A booking form needs the end date to come after the start date. Where does that rule belong?

Related

Sources

  1. MDN: Client-side form validation
  2. MDN: Using HTML form validation and the Constraint Validation API
  3. MDN: :user-invalid CSS pseudo-class
  4. web.dev Learn Forms: Help users enter the right data in forms
  5. OWASP: Input Validation
Sign in to report a mistake