Skip to content

A Form Error Must Be Reachable

The Course
•
18 min study

The decision

An error message isn't useful just because it's red. Someone using a keyboard or a screen reader needs three things after a failed submission:

  1. The draft kept. Retyping everything is a punishment.
  2. Each message tied to its field, so moving to the field announces the problem: aria-invalid marks the field, and aria-describedby points at the message's id.
  3. Focus on the first problem, so they don't have to hunt for it.

Read, predict, run

DraftForm.jsx already does the first two. The Server Action saveDraft returns the submitted values with the errors, and the inputs use them:

JSX
<input
  id="title"
  name="title"
  ref={fields.title}
  defaultValue={state.values.title}
  aria-invalid={Boolean(state.errors.title)}
  aria-describedby="title-error"
/>
<span id="title-error" className="fail">
  {state.errors.title}
</span>

lib/contract.js decides which field is "first", in the order they appear on the page:

JavaScript
export function run(errors) {
  return ["title", "minutes"].find((field) => Boolean(errors[field])) ?? null;
}

Run the lab, leave Title empty, type abc for Minutes, and press Save draft with the mouse. Predict which element has keyboard focus afterwards. (Press Tab once to find out: focus moves to the next element after the focused one.)

A Form Error Must Be Reachable Next.js · 7 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Study Library · Practice lab</strong> </header> {children} </body> </html> ); } import Cases from "./Cases.jsx"; import DraftForm from "./DraftForm.jsx"; export default function Page() { return ( <main> <h1>A Form Error Must Be Reachable</h1> <DraftForm /> <Cases /> </main> ); } "use server"; export async function saveDraft(previous, formData) { const values = { title: String(formData.get("title") ?? ""), minutes: String(formData.get("minutes") ?? ""), }; const errors = {}; if (!values.title.trim()) errors.title = "Enter a title."; const minutes = Number(values.minutes); if (!Number.isInteger(minutes) || minutes < 1) errors.minutes = "Enter the minutes as a whole number."; if (Object.keys(errors).length > 0) return { errors, values, saved: false }; return { errors: {}, values: { title: "", minutes: "" }, saved: true }; } import { run, examples } from "@/lib/contract.js"; const text = (value) => JSON.stringify(value) ?? "undefined"; export default async function Cases() { const results = await Promise.all( examples.map(async ([input, expected]) => { // Record the input before running, to show whether run changed it. const before = text(input); const actual = await run(input); return { input: before, expected, actual, kept: text(input) === before, pass: text(actual) === text(expected), }; }), ); return ( <section> <h2>Executable cases</h2> <p> Checks: {results.filter((row) => row.pass).length}/{results.length}{" "} passed </p> <table> <thead> <tr> <th>Input</th> <th>Expected</th> <th>Actual</th> <th>Input kept</th> </tr> </thead> <tbody> {results.map((row, i) => ( <tr key={i}> <td> <code>{row.input}</code> </td> <td> <code>{text(row.expected)}</code> </td> <td className={row.pass ? "pass" : "fail"}> <code>{text(row.actual)}</code> </td> <td className={row.kept ? "pass" : "fail"}> {row.kept ? "yes" : "no: run changed it"} </td> </tr> ))} </tbody> </table> </section> ); } "use client"; import { useActionState, useRef } from "react"; import { saveDraft } from "./actions.js"; import { run } from "@/lib/contract.js"; const initial = { errors: {}, values: { title: "", minutes: "" }, saved: false }; export default function DraftForm() { const [state, action, pending] = useActionState(saveDraft, initial); const fields = { title: useRef(null), minutes: useRef(null) }; return ( <form action={action} noValidate> <p> <label htmlFor="title">Title</label>{" "} <input id="title" name="title" ref={fields.title} defaultValue={state.values.title} aria-invalid={Boolean(state.errors.title)} aria-describedby="title-error" /> <span id="title-error" className="fail"> {state.errors.title} </span> </p> <p> <label htmlFor="minutes">Minutes</label>{" "} <input id="minutes" name="minutes" ref={fields.minutes} defaultValue={state.values.minutes} aria-invalid={Boolean(state.errors.minutes)} aria-describedby="minutes-error" /> <span id="minutes-error" className="fail"> {state.errors.minutes} </span> </p> <button disabled={pending}>{pending ? "Saving…" : "Save draft"}</button> <p role="status">{state.saved ? "Draft saved." : ""}</p> </form> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } export function run(errors) { return ["title", "minutes"].find((field) => Boolean(errors[field])) ?? null; } export const examples = [ [{ title: "Required", minutes: "Invalid" }, "title"], [{}, null], ];
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Check your prediction

Nothing in the form. The button had focus when you pressed it, but it's disabled while the action is pending, and a disabled element can't keep focus, so the browser drops it to the page itself. Tab starts again from the top of the page. Both messages are on screen and the draft is kept, but a screen reader user hears none of it unless they go looking.

The failure to avoid

Moving focus is a side effect, so it doesn't belong in render: calling focus() while rendering runs before the inputs are on the page, and runs again on every render. Tie it to a failed submission, not to typing: focusing on every keystroke would yank the cursor around.

Exercise

Focus the first problem

After a failed submission, move focus to the first invalid field: Title if it's empty, otherwise Minutes. A successful save must not move focus.

Your working space Next.js · 7 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Study Library · Practice lab</strong> </header> {children} </body> </html> ); } import Cases from "./Cases.jsx"; import DraftForm from "./DraftForm.jsx"; export default function Page() { return ( <main> <h1>A Form Error Must Be Reachable</h1> <DraftForm /> <Cases /> </main> ); } "use server"; export async function saveDraft(previous, formData) { const values = { title: String(formData.get("title") ?? ""), minutes: String(formData.get("minutes") ?? ""), }; const errors = {}; if (!values.title.trim()) errors.title = "Enter a title."; const minutes = Number(values.minutes); if (!Number.isInteger(minutes) || minutes < 1) errors.minutes = "Enter the minutes as a whole number."; if (Object.keys(errors).length > 0) return { errors, values, saved: false }; return { errors: {}, values: { title: "", minutes: "" }, saved: true }; } import { run, examples } from "@/lib/contract.js"; const text = (value) => JSON.stringify(value) ?? "undefined"; export default async function Cases() { const results = await Promise.all( examples.map(async ([input, expected]) => { // Record the input before running, to show whether run changed it. const before = text(input); const actual = await run(input); return { input: before, expected, actual, kept: text(input) === before, pass: text(actual) === text(expected), }; }), ); return ( <section> <h2>Executable cases</h2> <p> Checks: {results.filter((row) => row.pass).length}/{results.length}{" "} passed </p> <table> <thead> <tr> <th>Input</th> <th>Expected</th> <th>Actual</th> <th>Input kept</th> </tr> </thead> <tbody> {results.map((row, i) => ( <tr key={i}> <td> <code>{row.input}</code> </td> <td> <code>{text(row.expected)}</code> </td> <td className={row.pass ? "pass" : "fail"}> <code>{text(row.actual)}</code> </td> <td className={row.kept ? "pass" : "fail"}> {row.kept ? "yes" : "no: run changed it"} </td> </tr> ))} </tbody> </table> </section> ); } "use client"; import { useActionState, useRef } from "react"; import { saveDraft } from "./actions.js"; import { run } from "@/lib/contract.js"; const initial = { errors: {}, values: { title: "", minutes: "" }, saved: false }; export default function DraftForm() { const [state, action, pending] = useActionState(saveDraft, initial); const fields = { title: useRef(null), minutes: useRef(null) }; return ( <form action={action} noValidate> <p> <label htmlFor="title">Title</label>{" "} <input id="title" name="title" ref={fields.title} defaultValue={state.values.title} aria-invalid={Boolean(state.errors.title)} aria-describedby="title-error" /> <span id="title-error" className="fail"> {state.errors.title} </span> </p> <p> <label htmlFor="minutes">Minutes</label>{" "} <input id="minutes" name="minutes" ref={fields.minutes} defaultValue={state.values.minutes} aria-invalid={Boolean(state.errors.minutes)} aria-describedby="minutes-error" /> <span id="minutes-error" className="fail"> {state.errors.minutes} </span> </p> <button disabled={pending}>{pending ? "Saving…" : "Save draft"}</button> <p role="status">{state.saved ? "Draft saved." : ""}</p> </form> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } export function run(errors) { return ["title", "minutes"].find((field) => Boolean(errors[field])) ?? null; } export const examples = [ [{ title: "Required", minutes: "Invalid" }, "title"], [{}, null], ];
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Hint 1: the idea

useActionState gives you a new state object after every submission, and only then. An effect that depends on state therefore runs once per submission, after React has put the inputs on the page, which is exactly when focus should move.

Hint 2: a first step

Add a useEffect with [state] as its dependency that logs run(state.errors). Submit a few times: it should log "title", "minutes" or null. The refs in fields are already attached to the inputs, so fields.title.current is the title input.

Show one solution
JSX
useEffect(() => {
  const first = run(state.errors);
  if (first) fields[first].current.focus();
}, [state]);

Add it after the fields line, and import useEffect from react. run returns a field name, which is also a key of fields, so one line picks the right input. On success errors is empty, run returns null, and focus is left alone. Depending on [state.errors] instead would also work here, since a new object arrives each time; depending on nothing would focus only once, on the first render.

Explain it without the code

A form has five fields and the third and fifth are invalid. Write what a keyboard user experiences after pressing Save, with and without this effect, in two sentences.

Going further

Some forms also put a summary of all errors at the top in a role="alert" region, with links to each field. That helps long forms; for two fields, focus on the first problem is enough. React's useRef guide covers focusing elements.

Was this article helpful?

Your response is saved on this device.