Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 132 ยท Forms and Actions

Form Validation

Validate React forms the right way - when to show errors (change, blur, submit), accessible messages with aria-describedby, hand-written schemas, multi-step forms and async checks.

Validation is the part of a form that users notice most. A form that shouts "Invalid email!" the moment you type your first letter is annoying; a form that lets you press Submit and then silently does nothing is worse. Good validation answers three separate questions: what is wrong, when should the user hear about it, and how is the message delivered so that everybody, including people using a screen reader, can find and fix it.

React gives you no validation system of its own, and that is a feature. A form is state, validation is a function of that state, and you already know how to write both. This lesson builds up a small toolkit with nothing but state and plain functions: a validate function, a rule for when errors become visible, accessible error markup, a hand-written schema, a multi-step form and an asynchronous check. It continues from controlled inputs and forms, so skim that lesson first if value and onChange are new to you.

Validation is a function of the values

The simplest, most robust design is this: store only the field values (and a little UI state), and compute the errors during render with a pure function. You never have to remember to "clear the error" because there is no stored error to go stale.

JavaScript
function validateEmail(value) {
  if (value.trim() === '') return 'Email is required.';
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) return 'Enter an email like [email protected].';
  return '';
}

A validator returns an empty string when the value is fine, or a message when it is not. That is all. The interesting question is the second one: when do we show the message?

Choosing when to show errors

There are three classic timings, and each has a cost.

Timing Feels like Problem
On change (every keystroke) Instant feedback Scolds people before they finish typing: "not an email" after the letter a
On blur (when the field loses focus) The user finished this field, now check it Errors for fields never visited stay hidden until submit
On submit Calm, nothing interrupts The user fixes everything at the end, in one go

The best default for most forms is a mix: validate on blur, and once a field has shown an error, re-validate it on change so the message disappears as soon as the user fixes it. On submit, show every error at once. To do that you need two pieces of UI state: which fields have been touched (visited), and whether the form was submitted.

Use the selector below to feel the difference. The validator is identical in all three modes; only the rule for showing its result changes.

Three validation timings

Two details are worth noticing. First, the form has noValidate, which switches off the browser's own bubble messages so that ours are the only ones; we will come back to native validation below. Second, the error text is computed on every render (const error = validateEmail(email)), while showError is a separate decision. Computing and showing are different jobs.

A reserved line for the message (minHeight: '1.4em' above) stops the layout from jumping when an error appears. Layout shift while someone is typing is one of the most irritating details in a form.

Accessible error messages

Red text is not an error message for everyone. Sighted users see colour; screen-reader users need the error to be announced and connected to the field. Four small habits cover most of it:

  1. Put the message in a real element and give the input aria-describedby pointing at that element's id. The screen reader reads the message together with the field.
  2. Set aria-invalid="true" on the input while it is in error. Pass a boolean and React writes the attribute for you: aria-invalid={Boolean(error)}.
  3. Do not rely on colour alone: include text (and optionally an icon) in the message.
  4. On a failed submit, move focus to the first invalid field. Keyboard users should not have to hunt for what went wrong.

Because every field needs the same wiring, make a small Field component. It receives the label, the value, the error and a ref (in React 19, ref is an ordinary prop, so no forwardRef is needed).

An accessible sign-up form

Press Create account with an empty form: every error appears and focus jumps to the username field. Type a username and the first message vanishes immediately, because errors is recomputed from the new values; no code anywhere "clears" an error.

role="alert" makes a screen reader announce the message when it appears. Use it for errors that appear after an action. If the error is already in the page when it loads, aria-describedby alone is enough.

Native browser validation

HTML already has validation: required, minLength, pattern, type="email", and the :invalid CSS pseudo-class. It is free, fast and understood by browsers and assistive technology, but its bubble messages are hard to style and translate. A sensible plan is to keep the attributes (required, type, min, max, maxLength, so mobile keyboards and autofill behave) and either let the browser show its bubbles, or add noValidate to the form and show your own messages as above. Never rely on either alone for security: anyone can send a request that skips your page, so the server must validate again.

Validating with a hand-written schema

As forms grow, a long list of if statements gets hard to read. A schema describes each field's rules as data, and one small function applies them. Libraries such as zod or Yup do this at scale; the idea fits in a dozen lines, and writing it once makes those libraries easy to understand.

A tiny validation schema

Each rule is a function from a value to a message; the first failing rule for a field wins (break). Adding a rule to a field is one line, and the same schema could run on a Node server (see the JavaScript for React lesson for the array and object helpers used here). The <pre> shows the errors object so you can watch it change as you type.

Here is the same idea with a real library. This block is read-only: zod is not installed in our editor, and you would add it with npm install zod in your own project.

TSX
// Read-only example: needs "npm install zod" in a real project.
import { z } from 'zod';

const signUpSchema = z.object({
  name: z.string().min(2, 'Use at least 2 characters.'),
  age: z.coerce.number().int().min(18).max(120),
});

const result = signUpSchema.safeParse(Object.fromEntries(formData));
if (!result.success) {
  console.log(result.error.flatten().fieldErrors);
}

A schema library earns its place when you share the same rules between the browser and the server, or when you also want TypeScript types derived from the schema.

A disabled submit button is not a plan

It is tempting to disable the submit button until the form is valid, as the schema demo does. Used alone, this has a real problem: a disabled button cannot be focused or clicked, so the user gets no explanation of why they cannot proceed, and screen-reader users may not find it at all. Prefer an always-enabled button that, when pressed on an invalid form, shows every error and moves focus to the first one (as the sign-up form did). Disabling is fine for a different reason: while a submit is in flight, to prevent double submission (see Form Actions).

Multi-step forms

A long form is friendlier as steps. The pattern is: keep all values in one parent component (so going back never loses data), keep a step number, and validate only the fields of the current step when the user presses Next.

A three-step form

Go forward, come back, and notice the values are still there: the inputs unmount when the step changes, but the state lives in Wizard, which never unmounts. If each step were its own component with its own useState, going back would reset it. That is the rule of lifting state up in action.

Asynchronous validation

Some rules need a server: "is this username taken?" You cannot answer synchronously. The trap is the race: the user types ann, then anna; if the reply for ann arrives after the reply for anna, an out-of-date answer overwrites the right one. The fix is the same cleanup pattern as in useEffect: ignore a response once the effect that started it has been cleaned up. The demo simulates the server with a timer.

Username check with a stale-response guard

Two protections work together: the 200 ms setTimeout is a debounce (it waits for a pause in typing, so we do not call the server per keystroke), and the ignore flag discards any answer that belongs to an earlier value. aria-live="polite" makes screen readers announce the result without interrupting the user.

Guidelines worth remembering

  • Say what is wrong and how to fix it: "Use at least 8 characters" beats "Invalid password".
  • Do not erase the user's input because of an error, and never block pasting into password fields.
  • Validate on the server too. Client-side validation is a convenience, not a security measure.
  • Keep one source of truth: values in state, errors derived. Storing both invites mismatches.
  • Mark required fields in the label (or mark optional ones) and use proper type, autoComplete and inputMode attributes so browsers and phones help.
  • Validate formats loosely: for email, "contains an @ and a dot" is enough; the only real test is sending a message.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the most robust way to handle validation errors in a controlled form?

    Errors are a pure function of the values, so deriving them while rendering removes the need to remember to clear them and keeps values and errors in step.
  2. 2. Which attribute connects an error message element to its input for screen readers?

    aria-describedby holds the id of the element with the description, so assistive technology reads the message together with the field. htmlFor links the label, not the error.
  3. 3. A user presses Submit on an invalid form. What is the friendliest behaviour?

    Showing every error and focusing the first invalid field tells the user what to fix and lets keyboard users start immediately.
  4. 4. Why does the multi-step form keep its values in the parent component?

    A step component unmounts when you leave it, and unmounting destroys its state. State owned by a component that stays mounted keeps the values.
  5. 5. What does the ignore flag in the username check protect against?

    The cleanup function sets ignore to true when the name changes, so a late reply for the old name is discarded instead of being stored.

Summary

  • Store field values; derive errors in render with a pure validate function.
  • Decide separately when to show an error: blur plus change-after-error is a good default, and submit shows everything.
  • Use aria-invalid, aria-describedby, readable text and role="alert", and focus the first invalid field on a failed submit.
  • A schema (rules as data) keeps big forms readable; libraries such as zod do the same and can share rules with the server.
  • Prefer an enabled submit button that explains problems over a disabled one; disable only while a request is running.
  • Multi-step forms keep all values in one parent and validate only the current step on Next.
  • Guard asynchronous checks with a debounce and a cleanup flag so stale responses are ignored.
  • Always validate again on the server.

Next: Form Actions in React 19