The server rejects a value the client accepted; the user clicks “Save” and sees an unexplained “Operation failed”. Or the reverse happens: the server silently accepts a field the client never checked, and the faulty record distorts reports for months. In corporate business forms, validation rules usually live in three places: the form code in the browser, the API controller and database constraints. Over time they drift apart. Below, through code, we explain how to collect the rules in a single schema in web applications using TypeScript, asynchronous and cross-field rules, multi-step forms and showing server errors to the user.
The roles of client and server validation
The two layers have different purposes, and one doesn’t replace the other:
| Layer | Purpose | Is it trustworthy? |
|---|---|---|
| Client | Fast feedback, avoiding unnecessary requests, user experience | No; it can be bypassed |
| Server (application) | Data integrity, business rules, authorization checks | Yes; the single binding decision point |
| Database | The last line of defense: NOT NULL, UNIQUE, CHECK, foreign keys | Yes; it also protects against race conditions |
Client-side validation isn’t a security measure. A request can be sent directly to the API with browser developer tools, with curl or with an automation script; JavaScript can be turned off and fields can be changed in the DOM. The browser is the user’s machine, not yours. The server re-checks every field coming from the client as if it had never been validated. Server validation isn’t just a format check either: that the selected departmentId really exists and that the user is authorized to create records for that department are also the server’s job. For the security dimension of input validation, the OWASP Input Validation Cheat Sheet is a good reference; measures against malicious automated submissions are the subject of the preventing spam in web forms guide.
The schema-based validation approach
In schema-based validation, the structure and rules of the form data are defined once, declaratively; the same schema runs in both the browser and the server, and the TypeScript type is derived from the schema too. Zod, Valibot and Yup are used for this in the ecosystem. The examples are written with Zod; since some API details change between major versions, check the Zod documentation for the version you use.
// shared/schemas/purchase.ts — a module shared by client and server
import { z } from 'zod';
export const purchaseRequest = z.object({
title: z.string().trim().min(5, 'Title must be at least 5 characters').max(120),
amount: z.coerce.number().positive('Amount must be greater than zero'),
currency: z.enum(['TRY', 'EUR', 'USD']),
costCenter: z.string().regex(/^[A-Z]{2}-\d{4}$/, 'Format: AA-1234'),
deliveryDate: z.coerce.date(),
description: z.string().trim().max(2000).optional(),
});
export type PurchaseRequest = z.infer<typeof purchaseRequest>;
The practical results are these. The type derived with z.infer is shared by the API client, the form component and the server handler; when a field is added, the compiler shows the missing places. Transforms such as trim() normalize the data so it always reaches the server in the same form. z.coerce converts values that come from form fields as text into numbers or dates. There’s a trap here: empty text becomes 0 with Number(''), so handle the empty value separately in required numeric fields. If it isn’t checked, a request record with a zero amount looks “valid”.
On the server side, the same schema validates the request body. An unvalidated body never passes to the business logic:
// Server: Next.js Route Handler example
import { purchaseRequest } from '@/shared/schemas/purchase';
export async function POST(req: Request) {
const result = purchaseRequest.safeParse(await req.json());
if (!result.success) {
const fieldErrors: Record<string, string[]> = {};
for (const issue of result.error.issues) {
const field = issue.path.join('.') || '_form';
(fieldErrors[field] ??= []).push(issue.message);
}
return Response.json({ fieldErrors }, { status: 422 });
}
const request = result.data; // typed and normalized data
// authorization check + business rules + save
}
On the client, React Hook Form uses the same schema with zodResolver from the @hookform/resolvers package. Since the schemas sit in a separate module, it’s easy to check that server-specific dependencies (database client, secret keys) don’t leak into the client bundle: a lint rule that allows files under shared/schemas to import only zod and other schema files protects this boundary. If you use Next.js Server Actions, the same schema runs at the start of the action function instead of a Route Handler; the flow doesn’t change.
Asynchronous and cross-field rules
Some rules don’t fit into a single field. The end date being after the start, a description becoming mandatory when “Other” is selected, or a second approver being required above a certain amount are cross-field rules. In Zod, these are written at object level with refine, and the field the error is attached to is specified with path:
export const leaveRequest = z.object({
start: z.coerce.date(),
end: z.coerce.date(),
type: z.enum(['annual', 'excused', 'other']),
description: z.string().trim().optional(),
})
.refine((d) => d.end >= d.start, {
message: 'The end date can’t be before the start date',
path: ['end'],
})
.refine((d) => d.type !== 'other' || (d.description?.length ?? 0) > 0, {
message: 'A description is required when “Other” is selected',
path: ['description'],
});
Asynchronous rules (whether a tax number is registered in the system, whether a username is available) require a request to the server. On the client they’re only for user experience: they run when the field loses focus (onBlur) and with a short delay (debounce); a request isn’t sent on every keystroke. The definitive check is repeated on the server at submission, because the state may have changed between the two checks. For rules such as uniqueness, the final guarantee is the UNIQUE constraint in the database; the app should catch the constraint violation error and map it to the relevant field with a meaningful message. A raw SQL error doesn’t go to the user.
Know two behaviors commonly encountered in the field. First: an object-level refine doesn’t run while one of the fields has a type-level error (such as a missing required field or an invalid date); the user sees the date order error only after fixing those fields. If this isn’t acceptable, trigger the check separately on the client or group the fields in a single sub-object. Second: a Zod schema containing an asynchronous refine is run with parseAsync or safeParseAsync; synchronous parse throws an error in this case.
State and validation in multi-step forms
In custom web applications, long processes such as supplier registration, an employee onboarding form or preparing a quote are split into multi-step wizards. Three design decisions determine how the work goes:
- Split the schema into steps, but keep the whole too. Each step has its own schema; the full schema is the combination of them. The “Next” button runs only that step’s schema; the full schema runs on final submission and on the server. In Zod, object schemas are combined with
extend(and in Zod 3 also withmerge); sincemergeis marked as deprecated in Zod 4,extendshould be preferred. Cross-step rules are added to the full schema; since a schema withrefineapplied can no longer be extended, combining comes first, thenrefine. - Decide where the draft lives. For short wizards, form state inside the component is enough. For long processes, or if resilience to page refreshes is needed, store the draft on the server as a record in “draft” status; browser storage isn’t suitable for forms containing personal data. The tendency to move form state into a global store and its alternatives are discussed in the state management in React guide.
- Preserve data when going back. When the user returns to a previous step, the values they entered shouldn’t be lost. If a choice changed in an earlier step affects the rules of later steps, the relevant fields are re-validated.
Asking again in a later step for information already entered in an earlier step tires the user and conflicts with WCAG 2.2 criterion 3.3.7 Redundant Entry. Auto-fill previously entered values or make them selectable.
Showing server errors to the user
When the server rejects a value that passed the client, the error should appear in a form the user can fix, next to the right field. This requires a predictable error contract between the API and the front end. Without a contract, every screen interprets errors differently. The example above used the 422 status code and messages grouped by field name; if a standard error body is wanted for HTTP APIs, you can base it on the RFC 9457 (Problem Details for HTTP APIs) format and add field errors as an extension member.
// Client: mapping server errors to React Hook Form fields
const onSubmit = async (data: PurchaseRequest) => {
const response = await fetch('/api/purchase', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
});
if (response.status === 422) {
const { fieldErrors } = await response.json();
for (const [field, messages] of Object.entries(fieldErrors)) {
setError(field as keyof PurchaseRequest, { type: 'server', message: messages[0] });
}
return;
}
if (!response.ok) {
setError('root.server', { type: 'server', message: 'Could not save, please try again.' });
}
};
Things to check when displaying errors:
- The error message is associated with the field via
aria-describedbyand the field is marked witharia-invalid="true"; red color alone isn’t enough. - If there’s more than one error on submission, put a summary at the top of the form and move focus there or to the first invalid field.
- The message says what’s wrong and how to fix it: “The cost center must be in the format AA-1234” instead of “Invalid value”.
- The server’s internal error details (SQL errors, stack traces) aren’t passed to the user; they’re written to the server log, and the user is shown a general message and, if needed, a tracking ID. The support team uses that ID to find the relevant entry in the log.
- Don’t show errors on every keystroke while the user is typing; validate when the field loses focus. Once an error has been shown, updating it live during the correction is acceptable.
For details of accessible error display, see the forms section of the WCAG 2.2 developer guide.
Validation checklist
- There’s a single schema for each form; the client and server import it from a shared module.
- The server validates the request body with the schema before the business logic; unvalidated data doesn’t pass to the service layer.
- Fields not defined in the schema are ignored or rejected (against mass assignment risk); fields such as role, ownership and approval status aren’t taken from the client.
- Text fields have a maximum length; numeric fields have lower and upper bounds.
- The existence of ID and reference fields (department, project, customer) and the user’s permission for them are checked on the server.
- Uniqueness and relationship rules are also protected by database constraints; a constraint violation is turned into a message mapped to the field.
- Asynchronous checks are limited with debounce and repeated on the server at submission.
- The API error contract is documented; field errors and general errors are carried separately.
- Error messages are associated with fields accessibly and point the way to a fix.
- For fields containing personal data, retention and privacy notice obligations have been assessed separately; the topic is covered in the KVKK-compliant contact form guide.
If you’re developing business forms with approval flows, role-based fields and multi-step requests, we design the validation layer from the start too, within the scope of our form, request and approval systems service.
Frequently asked questions
If there’s client-side validation, is validating again on the server necessary?
Yes. Client-side validation is only for user experience; it’s easily bypassed with browser tools or a direct API request. For data integrity and security, the binding check is always done on the server.
Is there a risk in using the same schema on client and server?
There’s no risk as long as the schema module contains no server-specific dependencies. Rules requiring a database query go not into the shared schema but into an additional validation step on the server; otherwise server code can leak into the client bundle.
Which HTTP status code should be used for a validation error?
The common choices are 400 Bad Request and 422 Unprocessable Content. What really matters is that the code is consistent across the API and that field-level errors are returned in a predictable structure in the response body.
Should asynchronous validation run on every keystroke?
No. Checks that send a request to the server should run when the field loses focus, with a short delay. The result is for information only; the definitive check is repeated on the server at submission.