Form Validation Architecture: From Schema to UI
Build a layered form validation architecture with Zod schemas, progressive enhancement, and accessibility from the server boundary to the UI.
On this page
- Introduction
- Why a Single Schema Is the Source of Truth
- Validation at the Trust Boundary
- Progressive Enhancement: Validate Without JavaScript
- Wiring the Schema to the UI with React Hook Form
- Accessibility: Errors Must Be Programmatically Associated
- Reconciling Client and Server Errors
- Testing the Layers
- Async Validation, Dependent Fields, and Internationalized Errors
- Conclusion
Introduction
Form validation is where most applications first touch untrusted user input, and it is where most applications first cut corners. A common failure mode is to validate only on the client, in the component, with ad-hoc if (!email.includes("@")) checks that drift out of sync with the server and produce a different error message for the same input depending on where it is checked. The result is a form that passes in the browser and fails on the server with a message the user never sees, or a form that blocks valid input because the client rule is stricter than the server’s.
A robust validation architecture is layered: a single schema is the source of truth, the server validates against it at the trust boundary, the client validates against the same schema for immediate feedback, and the UI renders errors in a way that is accessible, progressive, and consistent. This article builds that architecture with Zod, React Hook Form, and a server boundary, but the layering transfers to any schema library and any framework.
Why a Single Schema Is the Source of Truth
The root cause of validation drift is duplication. When the client has one rule, the server has another, and the database has a third, they inevitably diverge. The fix is to define the shape of valid data exactly once and derive everything else from it. Zod is well suited to this because a schema is a runtime value that can be shared between client and server (in a monorepo or via a generated artifact) and because it produces structured, field-level errors you can map directly to form fields.
import { z } from "zod";
export const registrationSchema = z.object({
email: z.string().trim().toLowerCase().email("Enter a valid email address."),
password: z.string().min(12, "Use at least 12 characters.").regex(/[A-Z]/, "Include an uppercase letter.").regex(/[0-9]/, "Include a number."),
displayName: z.string().trim().min(2, "Display name is too short.").max(40, "Display name is too long."),
age: z.number().int().min(13, "You must be at least 13.").max(120),
acceptTerms: z.literal(true, { message: "You must accept the terms to continue." }),
});
export type Registration = z.infer<typeof registrationSchema>;
This schema is the contract. The server uses it to parse the incoming request body. The client imports it to drive field-level validation. The TypeScript type Registration is derived from it, so the code that consumes validated data is statically guaranteed to match. There is no second place to change when a rule evolves.
Validation at the Trust Boundary
The server is the trust boundary; everything the server believes has been validated must be validated by the server, regardless of what the client did. Client validation is a courtesy that improves UX; server validation is a guarantee that protects the system. Never trust a request because the client “already validated it.”
import { Router } from "express";
const router = Router();
router.post("/register", async (req, res) => {
const parsed = registrationSchema.safeParse(req.body);
if (!parsed.success) {
// Map Zod issues to { field: message } for the client.
const fieldErrors = parsed.error.flatten().fieldErrors;
return res.status(422).json({ errors: fieldErrors });
}
const data = parsed.data; // typed as Registration, guaranteed valid
if (await users.exists(data.email)) {
return res.status(422).json({ errors: { email: ["That email is already registered."] } });
}
const user = await users.create(data);
return res.status(201).json({ id: user.id });
});
Two things deserve emphasis. First, safeParse returns a result type rather than throwing, so validation failure is a normal control-flow branch, not an exception. Second, the asynchronous uniqueness check is separate from the schema parse. Schema validation is synchronous and pure; database checks are async and side-effecting. Mixing them (by writing a Zod refine that queries the database) couples your schema to your data layer and makes client-side reuse impossible. Keep schema validation structural and do contextual checks in the handler.
Progressive Enhancement: Validate Without JavaScript
A form that only works with JavaScript is a form that fails on slow connections, in older browsers, and for the significant minority of users who disable JavaScript. Progressive enhancement means the form submits and validates server-side with no JavaScript at all, and JavaScript layers on instant feedback as an enhancement. The building blocks are native: <form> with method and action, <label> associated by for, <input> with type, required, minlength, pattern, and novalidate only when you are taking over validation entirely.
<form method="POST" action="/register" novalidate>
<div>
<label for="email">Email</label>
<input id="email" name="email" type="email" autocomplete="email" required aria-describedby="email-error" />
<p id="email-error" class="error" aria-live="polite"><!-- server-rendered error --></p>
</div>
<!-- ... -->
<button type="submit">Create account</button>
</form>
When the server rejects, it re-renders the form with the error text populated and the field focused. The user gets a working, validated form with zero JavaScript. The React layer then hydrates on top, intercepts submit, runs the same schema client-side, and shows errors without a round trip — but if JavaScript never loads, the form still works.
Wiring the Schema to the UI with React Hook Form
React Hook Form manages field state and submission with minimal re-renders, and its zodResolver connects a Zod schema so the form’s validation is literally the shared schema. The same registrationSchema the server uses is imported here unchanged.
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
function RegistrationForm() {
const { register, handleSubmit, formState: { errors, isSubmitting } } = useForm<Registration>({
resolver: zodResolver(registrationSchema),
mode: "onBlur", // validate a field when the user leaves it
});
return (
<form method="POST" action="/register" novalidate onSubmit={handleSubmit(onValid)}>
<Field label="Email" id="email" error={errors.email?.message}>
<input id="email" type="email" autoComplete="email" aria-invalid={!!errors.email} {...register("email")} />
</Field>
<Field label="Password" id="password" error={errors.password?.message}>
<input id="password" type="password" autoComplete="new-password" aria-invalid={!!errors.password} {...register("password")} />
</Field>
<button type="submit" disabled={isSubmitting}>Create account</button>
</form>
);
async function onValid(data: Registration) {
const res = await fetch("/register", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) });
if (!res.ok) {
const { errors } = await res.json() as { errors: Record<string, string[]> };
// Reconcile server errors back into the form.
setError(errors);
} else {
redirect("/welcome");
}
}
}
The mode: "onBlur" choice matters for UX. Validating on every keystroke (onChange) is noisy and scolds users mid-typing; validating on submit only is silent until they finish. onBlur validates a field once the user leaves it, which is the moment they believe they are done with that field — feedback is timely without being nagging. After the first failed submit, switching to onChange for the affected fields is a common refinement so the user sees the error clear as they fix it.
Accessibility: Errors Must Be Programmatically Associated
An error message visible to a sighted user but invisible to a screen reader is not accessible. Two ARIA attributes do the work. aria-invalid="true" on the input tells assistive technology the field has an error. aria-describedby pointing to the error message’s id tells the screen reader to announce that message when the field is focused. aria-live="polite" on the error container announces dynamically inserted errors without interrupting other speech.
function Field({ label, id, error, children }: { label: string; id: string; error?: string; children: React.ReactNode }) {
const errorId = `${id}-error`;
return (
<div>
<label htmlFor={id}>{label}</label>
{children}
{error && <p id={errorId} className="error" role="alert">{error}</p>}
</div>
);
}
When the form has multiple errors after a submit, move focus to the first invalid field and announce a summary. A common pattern is a heading “Please fix the following” followed by a list of field links; focusing the summary on submit failure gives screen-reader users the overview a sighted user gets at a glance. Never rely on color alone to indicate an error — pair the red border with an icon and text.
Reconciling Client and Server Errors
The client and server both validate the same schema, but the server knows things the client cannot — that the email is already taken, that the rate limit is hit, that the session expired. When the server returns 422 with field errors, map them back into the form’s error state so the user sees them inline, exactly as if the client had caught them. This reconciliation is what makes the layered architecture feel seamless: the user does not know or care which layer caught the error; they see the same inline, associated, announced message either way.
For errors that are not field-specific (a 500, a network failure), show a form-level alert above the submit button with role="alert" and a clear retry path. Distinguish “your input was invalid” (422, fixable by the user) from “something went wrong on our side” (5xx, not fixable by the user) in both the HTTP status and the UI treatment.
Testing the Layers
Test the schema directly first — it is pure and fast. Assert that valid input parses and that each invalid input produces the expected field and message. Then test the server endpoint with a supertest or fetch-based test, asserting the 422 body shape for invalid input and the 201 for valid. Finally, test the form component with a browser-level test (Playwright): fill the field, blur, assert the error appears and is associated with the input via aria-describedby; submit invalid, assert the server error renders inline. The browser test is the one that catches the accessibility regressions the unit tests cannot see.
Async Validation, Dependent Fields, and Internationalized Errors
Not every validation is a pure function of the field’s value. The email-uniqueness check requires a database query; the postal-code validity depends on the selected country; the subdomain availability requires an API call. These async validations are essential, and they introduce a set of problems the synchronous schema does not have: latency, race conditions, and the cost of the check. Handle them deliberately rather than bolting them onto the schema.
The first rule of async validation is to debounce it. Checking email uniqueness on every keystroke fires a query per character and floods the database; checking it on blur fires one query when the user leaves the field, which is the right frequency. For fields where the user might type continuously (a subdomain name), debounce by 300–500ms after the last keystroke, so the check fires once when the user pauses rather than once per character. Cancel any in-flight check when a new one starts, so a slow response to an earlier value does not overwrite the result for the current value.
function useAsyncValidation<T>(value: T, validate: (v: T) => Promise<string | null>, delayMs = 400) {
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const handle = setTimeout(async () => {
const id = Symbol();
currentId = id;
const result = await validate(value);
if (currentId === id) setError(result); // ignore stale responses
}, delayMs);
return () => clearTimeout(handle);
}, [value]);
let currentId: symbol | null = null;
return error;
}
The stale-response guard is the detail that prevents a common bug: the user types “[email protected]”, a check starts, the user types “[email protected]”, a second check starts and finishes first returning “available”, the first check finishes second returning “taken”, and the field shows “taken” for an available value. The guard compares the response’s id to the current id and discards the stale one. Without it, async validation is a race condition visible to the user.
Dependent fields — where the validity of one depends on the value of another — are validated at the form level rather than the field level. The postal code is valid only for the selected country; the state is valid only for the selected country. Express this as a refinement on the form schema that reads multiple fields, and re-run it when any of the dependent fields change. Use z.refine or z.superRefine to produce a field-specific error from a multi-field check, so the error attaches to the right input rather than the form.
const addressSchema = z.object({
country: z.enum(["US", "CA", "GB"]),
postalCode: z.string(),
}).superRefine((data, ctx) => {
if (data.country === "US" && !/^\d{5}(-\d{4})?$/.test(data.postalCode)) {
ctx.addIssue({ code: "custom", path: ["postalCode"], message: "Enter a valid US ZIP code." });
}
if (data.country === "CA" && !/^[A-Z]\d[A-Z] \d[A-Z]\d$/.test(data.postalCode)) {
ctx.addIssue({ code: "custom", path: ["postalCode"], message: "Enter a valid Canadian postal code." });
}
});
Internationalize the error messages from the start, even if you ship only one language, because retrofitting i18n onto hardcoded strings is tedious and error-prone. The pattern is to keep the schema’s messages as message keys with parameters, and resolve them to the user’s locale at render time. Zod lets you pass a message to every check; store the key there and resolve it in the UI. A message like "password.too_short" with a parameter { min: 12 } resolves to “Use at least 12 characters.” in English and a different string in another locale, without the schema knowing the locale. This keeps the schema pure and testable, and puts the human-readable text in the locale files where translators expect it.
const schema = z.object({
password: z.string().min(12, { message: "password.too_short" }),
});
// In the UI, resolve the message key with parameters.
function resolveMessage(key: string, params: Record<string, unknown>): string {
return i18n.t(key, params); // "password.too_short" -> "Use at least {min} characters."
}
Server-side errors need the same treatment: return message keys and parameters from the API, not pre-rendered English strings, so the client renders them in the user’s locale. A server that returns “That email is already registered.” forces every client to display English; a server that returns { code: "email.already_taken" } lets each client localize. The schema, the server, and the client all speak in message keys, and the locale is applied once, at the edge closest to the user.
Conclusion
A form validation architecture that holds up in production has a single schema as the source of truth, validates at the server trust boundary on every request, layers client-side feedback on as a progressive enhancement, and renders errors with explicit ARIA associations so they reach every user. The discipline is in the layering: one schema, validated at the boundary, reflected in the UI, reconciled when the two disagree. Get that right and your forms become consistent, accessible, and secure by construction rather than by vigilance.
Report a problem with this articleOpens a pre-filled issue on GitHub.