Skip to content
ClapelloNotes by Barath
ReactCh 14 · 5/6
Core6 min readUpdated

React / 80

Validating forms the friendly way

TL;DR

Check fields when the user leaves them or submits, clear errors as soon as they're fixed, wire each message to its input with aria attributes, and let required and pattern help.

When to show the error

StrategyFeels likeUse it for
As you typeNagging: errors appear before you've finishedLive hints, like a password strength meter
On blur (leaving the field)Fair: you finished, then get toldMost fields
On submitCalm, but you find out lateShort forms

The friendly mix: show an error on blur or submit, then re-check on every keystroke so it vanishes the moment it's fixed. Try the three strategies here:

When should the error appear?

Try it

aria-invalid: not set

aria-invalid: not set

Pick a strategy, then type one letter in Email and Tab away. 'As you type' nags straight away; 'on blur' waits until you leave; 'on submit' waits for the button. Once an error shows, fixing it clears it instantly.

Store less, derive errors

Errors are just a function of the values, so calculate them on every render instead of keeping them in state. You only store what the user has done: which fields they left (touched) and whether they tried to submit.

validate.js
export function validate({ email, password }) {
  const errors = {};
  if (!email) errors.email = "Enter your email.";
  else if (!email.includes("@")) errors.email = "Email needs an @.";
  if (password.length < 8) errors.password = "Use at least 8 characters.";
  return errors;
}
SignupForm.jsx
import { useState } from "react";
import { validate } from "./validate";
 
export default function SignupForm() {
  const [values, setValues] = useState({ email: "", password: "" });
  const [touched, setTouched] = useState({});
  const [submitted, setSubmitted] = useState(false);
 
  const errors = validate(values);
  const emailError = submitted || touched.email ? errors.email : undefined;
 
  function handleChange(e) {
    setValues({ ...values, [e.target.name]: e.target.value });
  }
  function handleBlur(e) {
    setTouched({ ...touched, [e.target.name]: true });
  }
  function handleSubmit(e) {
    e.preventDefault();
    setSubmitted(true);
    const firstBad = Object.keys(errors)[0];
    if (firstBad) {
      e.currentTarget.elements[firstBad].focus(); // jump to the problem
      return;
    }
    console.log("Signing up", values);
  }
  // return ( …see the JSX tab… );
}
SignupForm.jsx (return)
return (
  <form onSubmit={handleSubmit} noValidate>
    <label htmlFor="email">Email</label>
    <input
      id="email"
      name="email"
      type="email"
      value={values.email}
      onChange={handleChange}
      onBlur={handleBlur}
      aria-invalid={emailError ? true : undefined}
      aria-describedby={emailError ? "email-error" : undefined}
    />
    {emailError && <p id="email-error">{emailError}</p>}
 
    {/* password: the same pattern */}
    <button type="submit">Sign up</button>
  </form>
);

On a failed submit, focus moves to the first broken field, so keyboard and screen reader users land right on the problem.

Showing errors accessibly

A red border is invisible to a screen reader and hard to see for colour-blind users. Three bits of wiring fix that:

<label htmlFor="email">Email</label>
<input
  id="email"
  aria-invalid="true"
  aria-describedby="email-error"
/>
<p id="email-error">Email needs an @.</p>

htmlFor ↔ id

Names the field

tapping the label focuses the input; readers say "Email"

aria-invalid

Marks it wrong

readers add "invalid entry"; style it with a ring, not colour alone

aria-describedby ↔ id

Links the message

readers say "Email needs an @." when the field gets focus
Matching ids are the wiring. The label names the input, aria-invalid says it's wrong, and aria-describedby points to the message a screen reader reads out next.
  • A real label: <label htmlFor="email"> matched to id="email".
  • aria-invalid="true" on the input while it has an error.
  • aria-describedby pointing at the message's id, so it's read out when the field is focused.
  • Show the error as text (plus an icon if you like), never colour alone.

Hard-coded ids clash if the component appears twice on a page. In reusable components, make them with useId(): const id = useId(); then `${id}-email`.

Native validation: required, pattern & co.

The browser can check simple rules by itself, with no JavaScript:

<input name="email" type="email" required />
<input name="pin" inputMode="numeric" pattern="[0-9]{6}" title="6 digits" />
<input name="qty" type="number" min={1} max={10} />
<input name="nickname" minLength={2} maxLength={20} />
  • If a rule fails, the browser blocks the submit (your onSubmit doesn't run) and shows its own bubble.
  • pattern must match the whole value: [0-9]{6} means exactly six digits, not "contains six digits".
  • type="email" also brings up the email keyboard on phones.

When you show your own messages, add noValidate to the <form>. It turns off the browser's bubbles and blocking, but keeps the helpful keyboards. Either way, validate again on the server: browser checks are for convenience, and anyone can bypass them.

Don't disable submit until it's valid

Don't

Grey until perfect

<button type="submit" disabled={!isValid}>
  Sign up
</button>

The user can't tell what's missing, and a disabled button can't be focused, so keyboard users may never find it at all.

Do

Always clickable, disabled only while sending

<button type="submit" disabled={isSending}>
  {isSending ? "Signing up…" : "Sign up"}
</button>

A click on a broken form shows every error and focuses the first one. Disabling while sending stops double submits.

React 19 can track "sending" for you with useFormStatus and useActionState. That's chapter 16.

Gotchas

Recall

Can you answer these?

0/5

Answer out loud (or in your head) before you tap. That's what makes it stick.

Saved on this device only. No login.