Form validation in React: client rules, server errors, and a single contract
Forms are where a web application negotiates with its users the most. The user types something, the application objects, the user corrects it. When this negotiation is poorly designed, the results are familiar: fields painted red before anything has been typed, a server error turning into a generic "Something went wrong" banner at the top of the screen, a button clicked twice creating two orders.
In this post I describe treating React forms not as a pile of individual field checks but as a contract between client and server. The goal is to keep rules in one place, show errors at the right moment, and carry the server's response back to the user in a meaningful way.
The server owns validation
The first principle is simple but often forgotten: client-side validation is a user experience feature, not a security measure. Every check in the browser can be bypassed; a request can be sent directly to the API. So the final enforcer of every rule is the server.
This principle makes it easier to split validation into two groups:
- Format rules: required fields, length, email format, numeric ranges. They only look at the entered data and can be checked instantly on the client.
- State rules: "this email is already registered", "insufficient stock", "the coupon has expired". They depend on the current state of the system, and only the server can decide.
By catching the first group early, the client reduces unnecessary requests and waiting. For the second group, the job is to translate the server's response to the right field and into the right language. When you can present both in the same form with the same error display, the user does not notice where an error came from, and they do not need to.
Keeping rules in a single schema
Scattering format rules across the onChange handler of every input soon means no longer knowing which rule lives where. Instead, defining the data the form expects as a schema lets you produce both validation and the TypeScript type from the same source. For example, with zod:
import { z } from "zod";
export const signupSchema = z.object({
email: z.string().trim().email("Enter a valid email address."),
password: z.string().min(12, "Password must be at least 12 characters."),
displayName: z.string().trim().min(2, "Name must be at least 2 characters.").max(50),
});
export type SignupInput = z.infer<typeof signupSchema>;
export function validate(values: SignupInput) {
const result = signupSchema.safeParse(values);
if (result.success) return { data: result.data, errors: {} };
const errors: Record<string, string> = {};
for (const issue of result.error.issues) {
const field = issue.path.join(".");
errors[field] ??= issue.message;
}
return { data: null, errors };
}
Two small decisions matter here. First, only the first error message per field is kept; showing the user three separate objections at once does not help. Second, transformations like trim live inside the schema, so the data that gets submitted is the same data that was validated.
Where possible, keep the schema's rules aligned with server-side validation. Full sharing is not always possible, especially when the backend is .NET. But making sure that at least rules such as length limits and required fields do not differ between the two sides reduces "the client accepted it, the server rejected it" surprises.
When to show an error
The right rule shown at the wrong time still produces a bad experience. Seeing "Enter a valid email" the moment the user types the first letter into the email field is like being corrected in the middle of an unfinished sentence.
The flow I use by default is this:
- A field shows no error until the user leaves it (
blur). - Once a field counts as "touched", it is revalidated on every change, so the message disappears as soon as the user fixes the error.
- When the submit button is pressed, all fields count as touched and all errors become visible.
const [values, setValues] = useState<SignupInput>(initialValues);
const [touched, setTouched] = useState<Record<string, boolean>>({});
const [submitted, setSubmitted] = useState(false);
const [serverErrors, setServerErrors] = useState<Record<string, string>>({});
const { errors } = validate(values);
const visibleError = (field: keyof SignupInput) =>
serverErrors[field] ??
(touched[field] || submitted ? errors[field] : undefined);
Deriving errors from the values on every render, instead of storing them as separate state, eliminates inconsistencies between value and error. An error is a function of the value, not a second source that has to be kept in sync by hand. Server errors are the exception: they cannot be derived from the value, so they are kept separately and cleared when the related field changes.
Mapping server errors to fields
If the backend is ASP.NET Core, validation errors usually arrive in Problem Details format: a 400 status code and an errors object mapping field names to lists of messages. That structure is enough for the client to put an error on the right field; all it takes is a small translation layer.
type ValidationProblem = {
title?: string;
errors?: Record<string, string[]>;
};
export function mapServerErrors(problem: ValidationProblem) {
const fieldErrors: Record<string, string> = {};
for (const [key, messages] of Object.entries(problem.errors ?? {})) {
const field = key.charAt(0).toLowerCase() + key.slice(1);
if (messages.length > 0) fieldErrors[field] = messages[0];
}
return fieldErrors;
}
The thing to watch is that field names match. The server may say Email while the client expects email; nested objects may produce paths like Address.City. Doing this conversion in a single function is better than solving it again in every form.
Not every error belongs to a field. Messages such as "your account is suspended" or "this operation cannot be performed right now" concern the form as a whole. Keep a separate area above the form for these, and route any error that cannot be mapped to a known field there. Making sure no error is silently lost matters more than placing every one of them perfectly.
Submission state and double submits
Submission is the most fragile moment of a form. On a slow network the user may press the button a second time, the form may be changed in the meantime, or the user may leave the page.
The basic safeguards are:
- Disable the button while the submission is in progress and show the state clearly. Managing this with a single
statusvalue held inuseState(idle,submitting,error) prevents several booleans from contradicting each other. - If a previous request needs to be cancelled, use
AbortController; cancel it when the component unmounts as well, so you do not try to write the result to a screen that no longer exists. - The real protection is, again, on the server. For operations where repetition is harmful, such as orders or payments, the client can generate an idempotency key when the form opens and send it with the request; the server does not process a second request with the same key as a new operation.
Disabling the button stops most double clicks, but it does not stop network retries, tab refreshes, or requests coming from two different devices. The client-side measure fixes the experience; the server-side measure protects the data.
Presenting errors accessibly
A red border and a small line of text below it may be enough for a sighted user; for someone using a screen reader, the information that the field is invalid may never arrive. A few attributes close that gap:
<label htmlFor="email">Email</label>
<input
id="email"
type="email"
value={values.email}
aria-invalid={emailError ? true : undefined}
aria-describedby={emailError ? "email-error" : undefined}
onChange={(e) => update("email", e.target.value)}
onBlur={() => touch("email")}
/>
{emailError && <p id="email-error">{emailError}</p>}
When a submission fails, moving focus to the first invalid field saves the user from hunting for the error in a long form. Using role="alert" for the general error area above the form ensures the message is announced by screen readers. Expressing the error in text, not only in color, is part of the same principle.
Testing validation
The biggest gain from moving rules into a schema and small pure functions is testability. validate and mapServerErrors can be verified with unit tests without any React dependency: boundary lengths, inputs with whitespace, unrecognized server fields.
At the component level, testing behavior from the user's point of view is more valuable: does an error appear when submitting with an empty field, does it disappear once fixed, does the message show up under the right field when the server returns 400, is the button disabled while submitting. Replacing the network layer with a fake response and running these scenarios prevents changes to form logic from silently breaking something.
Closing
A good form tells the user what went wrong at the right moment, in the right place, and in an understandable way. You do not need heavy infrastructure for this: keeping rules in a single schema, deriving errors from values, writing a small layer that maps the server's response to fields, and managing submission state with a single value makes most forms reliable. When you treat the server as the real owner of validation and position the client as a layer that improves the experience, each side does its own job and the user never feels the boundary between them.