What you'll learn: By the end of this lesson you will be able to choose between controlled, uncontrolled and native forms, keep every validation rule in one schema, decide when an error becomes visible, make errors usable with a keyboard and a screen reader, map a server's answer back onto the field it is about, and test the whole flow without a browser.
Picture a paper form handed across a counter. A good clerk does not shout after every letter you write, and does not wait an hour to say the first box was blank. They glance at a box when you move on, and at the end point at exactly what is wrong. When another office says "already registered", they write that next to the right box.
The running example is the sign-up form of a grocery marketplace: email, password and a confirmation. Three fields are enough to show a rule that needs one value, a rule that needs two, and an error only a server can know.
The core idea
- A form has four kinds of state: the values typed; the errors they deserve; the progress (fields touched, submit attempted, request in flight); and the server's answer. Only values and progress are real state. Errors are derived: the same values always give the same errors.
- The rules live in one place: a schema applied by one pure function, which the browser and a server can both run.
- Timing is separate from the rules. Change, blur and submit use the same rules and differ only in when a message becomes visible.
- The server is the authority. MDN's form validation guide says client-side validation should not be treated as an exhaustive security measure and that data passed to the server must never be trusted.
Where the values live
react.dev describes the two styles. An <input /> is uncontrolled: the DOM holds its value, and defaultValue only sets the starting text. To make it controlled you pass value (or checked) and React forces the input to show it; you must also provide onChange, which fires on every keystroke, or typing becomes impossible. An input cannot switch between the two over its lifetime. A third style needs no React state: the browser's own constraint validation, with attributes such as required, minlength and type="email".
| Style | Who holds the value | Re-renders per keystroke | Good for |
|---|---|---|---|
| Controlled | React state | One per keystroke | Live rules, derived UI, masks, dependent fields |
| Uncontrolled | The DOM; read with FormData on demand |
None, until you ask | Large forms, simple submit-time checks |
| Native attributes | The DOM and the browser's validator | None | Plain forms, a baseline for both of the others |
MDN's FormData page says it builds key and value pairs from form fields in the format a form would use for multipart/form-data; an uncontrolled form reads its values from it when the user submits.
Figure 1. Three ways to hold a form's values
How to read this: both styles end up calling the same function. The choice is where the values live and how often React renders, never what the rules are.
One schema, one function
Rules are small functions that return a message or nothing. Each field has a list, run in order; the first failure is the message, so a field never shows two at once.
Illustration 1: the minimal example
type Rule = (value: string, all: Values) => string | null;
const required = (message: string): Rule => (value) => (value.trim() === "" ? message : null);
const minLength = (n: number): Rule => (value) =>
value.length >= n ? null : `Use at least ${n} characters (you have ${value.length}).`;
function validateField(rules: readonly Rule[], value: string, all: Values): string | null {
for (const rule of rules) {
const message = rule(value, all);
if (message !== null) return message;
}
return null;
}
Notice that a rule receives all values. That is what lets "confirm password" depend on "password", which a per-field required attribute cannot express. The messages say what is wrong and what the limit is ("you have 5"): MDN's guidance for error messages is to display explicit messages and point out exactly where the error occurs.
Illustration 2: the realistic example, from the lab
The lab's validate.ts is this idea for the three fields. Its demo runs the schema over several value sets. Expected output, captured from a real run (node src/demo.ts in examples/frontend/labs/form-state-and-validation, copied from examples/frontend/golden/form-state-and-validation.txt), in full:
=== 1. one schema, one function: every field at once
empty form
values : {"email":"","password":"","confirm":""}
email Enter your email address.
password Choose a password.
confirm Type the password again.
typo in email, short password
values : {"email":"ada.example.com","password":"short","confirm":"short"}
email Enter an email address such as name@example.com.
password Use at least 8 characters (you have 5).
passwords differ
values : {"email":"ada@example.com","password":"correct horse","confirm":"correct hose"}
confirm The two passwords do not match.
all good
values : {"email":"ada@example.com","password":"correct horse","confirm":"correct horse"}
result : valid
=== 2. rules run in order; the first failure is the message
email "" -> Enter your email address.
email " " -> Enter your email address.
email "ada" -> Enter an email address such as name@example.com.
email "a@b" -> ok
email "a@@b" -> Enter an email address such as name@example.com.
email "a b@c" -> Enter an email address such as name@example.com.
=== 3. a message that says what the limit is (minimum 8)
password length 0 -> Choose a password.
password length 1 -> Use at least 8 characters (you have 1).
password length 7 -> Use at least 8 characters (you have 7).
password length 8 -> ok
=== 4. a cross-field rule: confirm depends on password
confirm before : ok
password edited, confirm untouched : The two passwords do not match.
=== 5. a server error uses the same field names
email <- That email is already registered.
client-side check of the same values: valid (the server still knows something the schema cannot)
Read it off. A blank email gets the "required" message, not the "format" one, because rules run in order. The email rule is deliberately loose: a@b passes, since only sending a message proves an address is real. Block 4 shows the cross-field rule: editing the password invalidates a confirmation the user did not touch, so the schema must re-run on every change. Block 5: the client says "valid" and the server still has the final word.
When an error becomes visible
The schema can run on every render. What the user should see is another matter.
| Timing | Shows an error when | Cost |
|---|---|---|
| On change | after the first keystroke in that field | Scolds a half-typed email ("a" is not an address yet) |
| On blur | after the user leaves the field | Late feedback inside a long field; no feedback for untouched fields |
| On submit | after the first attempt | The user sees everything at once, at the end |
A good default combines them: show nothing on a pristine form, show a field's error on blur, and after a failed submit validate live so a fixed field's error disappears as the user types. MDN's aria-invalid page says not to set aria-invalid="true" on empty required elements until the user attempts to submit, because they may still be filling the form out.
Figure 2. When a field's error is shown
How to read this: only the arrow from Touched to Shown (or the submit attempt) makes an error visible. The rules themselves run all the time, since they are derived; the diagram is about what the user is shown.
Accessible errors
An error that only turns a border red is invisible to many users. WCAG 3.3.1 (Level A) says that when an input error is automatically detected, the item in error is identified and the error is described to the user in text; the Understanding page says colour may supplement the text, not replace it. The lab builds the usual pieces.
- A visible
<label>for every input, tied byhtmlFor. - The message is text next to the field, and the input points to it with
aria-describedby, which MDN describes as identifying the element that describes the element it is set on, byid. The lab sets it only while there is an error. aria-invalid="true"while the value is invalid. MDN says to pair it with messaging and namesaria-errormessageas one option; the lab usesaria-describedby, and this lesson does not compare support between the two.- A summary after a failed submit, one link per field. The lab marks it
role="alert", which MDN says is equivalent toaria-live="assertive"andaria-atomic="true". - Focus moves to the first invalid field, done in an effect after the error text and attributes are in the DOM.
autocompletetokens (email,new-password); MDN saysnew-passwordfits a new-password or confirm-new-password field.
Two cautions from MDN's alert page: an alert is announced when its content changes, so the element should exist before the message is put into it, and alerts must be used sparingly. The lab's summary appears only after a submit attempt. What a given screen reader announces is something these tests cannot show: they check the markup and focus the code produces.
The browser's own validation
Attributes such as required, minlength and type="email" let the browser validate without your code, and the Constraint Validation API exposes the result: validity flags such as valueMissing, typeMismatch and tooShort, checkValidity() to check statically (no message is shown), reportValidity() to report failures to the user, and setCustomValidity(message), where an empty string means valid and any other string is an error. Two MDN details matter: minlength is only checked on user-provided input, not for a value set from script; and novalidate turns off the browser's own error bubbles without disabling the API or the :invalid pseudo-class.
Native validation is a good baseline but a poor interface on its own: the wording is the browser's and is hard to style or to map from a server. Many teams keep the attributes, add noValidate and show their own schema's messages.
The server's answer
Some facts only the server has: this email is already registered, this coupon expired. The form must treat the answer as data, not as a thrown error.
- The reply names fields, in the same vocabulary as the schema:
{ errors: { email: "..." } }. - The form maps each message onto its field, shows it in the same place as a client message, and moves focus to the first one. What the user typed stays.
- The message is dropped when that field is edited, because it described the old value.
- A second submit while one is in flight does nothing, or the form posts twice when the user presses Enter.
Figure 3. A submit that the server rejects
How to read this: the server's error is not a separate kind of UI. It lands in the same slot as a client error, so the accessibility work is done once.
Illustration 3: the failure case, from the lab
The lab's ControlledForm takes a server function. With a server that answers "already registered", the tests assert that the message is attached to Email, that focus moves to it, that the other values are kept, that editing the field removes the message, and that pressing Enter while a request is in flight does not call the server a second time.
The other side of this topic
The server runs its own validation on the same data, because a script or a modified client skips yours. The shared schema, one place for rules that both sides can import, keeps the two from drifting; the server can also add checks the client never could, such as uniqueness.
Trade-offs
| Choice | Gain | Cost |
|---|---|---|
| Controlled fields | Live derived UI, easy testing | A render per keystroke |
| Uncontrolled fields | Fewer renders, less code | Live feedback needs extra wiring |
| Validate on change | Immediate | Scolds unfinished input |
| Validate on blur, then live | Calm, then responsive | A little more state |
| One shared schema | No drift between client and server | Must stay free of browser-only code |
Build it
The lab examples/frontend/labs/form-state-and-validation has src/validate.ts (the schema), src/forms.tsx (a ControlledForm with three timings, an UncontrolledForm, and a NativeForm) and tests that type with user-event, so blur and focus really happen. They run in jsdom, a model of the DOM; they check markup, focus and attributes, not what a screen reader says or how the page looks.
cd examples/frontend/labs/form-state-and-validation
../../node_modules/.bin/vitest run
node src/demo.ts
Verified. The 23 tests in two files passed with Node 26.13.1 and Vitest 5.1.0, and the type check passed. They cover the pure schema, the three timings, focus and ARIA attributes, the summary links, server errors, double submits, a controlled form committing on every keystroke while an uncontrolled one commits none until asked, and the ValidityState flags that jsdom produces. This session added src/demo.ts and a demo script, which print the output above.
Break it. In validate.ts, temporarily swap the two email rules so the format rule runs first, run the tests: three fail (the schema's "one message per field" test, the rule-order test and the label test), because an empty email now gets the format message. Restore the order and re-run.
Stretch. Add a "username is taken" check that calls a fake server on blur, and decide how it interacts with the double-submit guard and with a late reply for an older value.
In practice: the sign-up form that lost its errors
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
A marketplace sign-up form relies on browser validation bubbles. Support reports users submitting repeatedly because "nothing happened" when the server rejected an email, a screen-reader user who could not find the wrong field, and message wording that differs between devices.
Starting architecture
Figure 4. Browser bubbles, then a generic failure
How to read this: the warning boxes are the gaps. Client errors are inconsistent, and the server's field errors never reach the fields.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
Shared schema, own messages, noValidate |
Consistent text, mapped server errors | A form component and tests | Drift if schema is copied |
| A form library | Less code to write | A dependency and its conventions | Hidden timing rules; still needs the server mapping |
The decision
| Field | Decision record |
|---|---|
| Context | Browser messages vary, server errors are not shown on fields, double submits happen. |
| Decision | One schema shared with the server; validate on blur, then live after a failed submit; labelled inputs with text errors, aria-invalid, aria-describedby, a summary and focus on the first problem; server field errors mapped onto fields; submit disabled while in flight. |
| Consequences, good | Consistent, testable, accessible errors; no duplicate sign-ups from repeat clicks. |
| Consequences, bad | More code than attributes alone; the schema must stay free of browser-only code. |
| Revisit when | The number of forms makes a library worth its conventions. |
Rollout and verification
- Pin the behaviour with tests: each timing, the focus move, the summary, the server mapping.
- Keep the HTML attributes, and add
noValidateonly once the custom messages are in place. - Try it with a keyboard and a screen reader; the tests cannot say what is announced.
- Watch repeat submissions on the sign-up endpoint after release.
The 2 a.m. failure
Overnight, sign-ups fall. A new field was added to the form, but the server's error key for it ("phone") does not match the schema's field name ("mobile"). The form finds no field for the message, shows nothing, and users see a button that does nothing.
First three checks: (1) compare the server's error keys with the schema's field names; (2) look at what the form does with a key it does not know; (3) reproduce with the server's real response. Mitigation: show unmatched messages in the summary instead of dropping them. Follow-up: share the field names between client and server and add a test that fails on an unmapped key.
Architect's notes
- Derive errors; do not store them. Store values and progress; compute the rest.
- Separate rules from timing. One schema, a policy for when to show it.
- Make the server's answer data. Field-keyed, shown in the same slot as client errors.
- Never lose what the user typed on a failed submit.
- Accessibility is part of the design: label, text,
aria-invalid, description, summary, focus.
Common mistakes
- Validating on every keystroke and scolding half-typed input.
- Showing errors only as colour.
- Dropping unmapped server errors.
- Allowing double submit while a request is in flight.
- Trusting client validation as security.
- Setting
aria-invalidon empty fields before the user has tried to submit.
Key takeaways
- Form state is values plus progress; errors are derived from one schema.
- Timing is a policy: blur first, live after a failed submit.
- Errors are text, tied to the field, summarised, with focus on the first one.
- Server errors are field-keyed data, shown in the same slot and dropped when the field is edited.
- Native attributes are a baseline; the server validates again.
Practice exercises
Exercise 1: Starter (30 min). Run the demo and add a value set that makes only the confirmation fail. Predict the output first.
Exercise 2: Intermediate (2 hours). Add a "phone" field with a rule that accepts spaces and dashes. Write the schema tests before the component change.
Exercise 3: Intermediate (2 hours). Make the summary show a server message whose field name is unknown. Write the test first.
Exercise 4: Advanced (half day). Count renders per keystroke with a Profiler, then split the controlled form so typing in one field does not re-render the others.
Related reading
In this course:
- React Effects and Synchronization: why the focus move runs in an effect after the DOM is updated.
- Debouncing and Throttling: checking a field against a server without a request per keystroke.
- URL State: what does belong in the address bar, unlike half-typed input.
- Server Actions and Server-Driven Mutations: another way to submit a form and get field errors back.
Official documentation
- React:
<input>: controlled and uncontrolled inputs,value,defaultValue,onChange. - MDN: Client-side form validation: built-in attributes,
setCustomValidity,novalidate, server-side validation. - MDN: Constraint validation:
ValidityState,checkValidity()andreportValidity(). - MDN:
minlength: checked only on user input. - WCAG 2.2: Understanding 3.3.1 Error Identification: errors identified and described in text.
- MDN:
aria-invalidandalertrole.