React / 80
Validating forms the friendly way
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
| Strategy | Feels like | Use it for |
|---|---|---|
| As you type | Nagging: errors appear before you've finished | Live hints, like a password strength meter |
| On blur (leaving the field) | Fair: you finished, then get told | Most fields |
| On submit | Calm, but you find out late | Short 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 itStore 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.
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;
}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… );
}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
aria-invalid
Marks it wrong
aria-describedby ↔ id
Links the message
- A real label:
<label htmlFor="email">matched toid="email". aria-invalid="true"on the input while it has an error.aria-describedbypointing at the message'sid, 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
onSubmitdoesn't run) and shows its own bubble. patternmust 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.
