Sub topic 10
Cross-field rules with refine
This chapter assumes you can build a form with useForm, register and handleSubmit, and that you have connected a Zod schema with zodResolver. It also assumes you can read basic TypeScript generics.
Why field-level rules are not enough
Rules like min(8) or email() look at one value. Some rules compare several values:
- A password and its confirmation must match.
- An end date must come after a start date.
- A maximum price must not be lower than the minimum price.
A rule attached to one field cannot see its neighbors. You attach these rules to the object that contains the fields, using refine.
The basic pattern
refine takes a check function and an options object. The function receives the whole parsed object and returns true when the data is valid.
import { z } from "zod";
const passwordSchema = z
.object({
password: z.string().min(8, "Use at least 8 characters"),
confirmPassword: z.string(),
})
.refine((data) => data.password === data.confirmPassword, {
message: "Passwords do not match",
path: ["confirmPassword"],
});The options object has two parts that matter here:
messageis the text the user sees.pathis an array that says where the error is reported.
Why path matters
Without path, the issue belongs to the object itself, so its path is empty. zodResolver has no field to attach it to, and the message ends up under the root of formState.errors. Your errors.confirmPassword check never sees it, and the user gets no feedback.
With path: ["confirmPassword"], the resolver places the error at errors.confirmPassword. The message then appears next to that input like any other field error. Pick the field the user should fix. For a password mismatch, that is usually the confirmation field.
For nested data, the path follows the structure: path: ["dates", "end"] maps to errors.dates?.end. For array items, include the index: path: ["items", 2, "name"].
How a refine fits into the validation flow
On submit (or on a validation event), the resolver runs the whole schema against the current values. Field rules run first. The object-level refine runs after them. The resolver collects every issue and converts the issue paths into the errors object.
There is one rule about ordering to remember. If a field fails with a type-level problem, such as undefined where a string is required, Zod stops before the object-level check, because the data it would compare is not trustworthy. Text inputs always give strings (an empty input gives ""), so with defaultValues set for every field the refine runs as you expect. A missing default is a common reason a cross-field error "never shows up".
Using it in a form
The component needs nothing special. The refine error arrives through the same errors object as every other error.
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
const passwordSchema = z
.object({
password: z.string().min(8, "Use at least 8 characters"),
confirmPassword: z.string(),
})
.refine((data) => data.password === data.confirmPassword, {
message: "Passwords do not match",
path: ["confirmPassword"],
});
type PasswordValues = z.infer<typeof passwordSchema>;
export function PasswordForm() {
const {
register,
handleSubmit,
formState: { errors },
} = useForm<PasswordValues>({
resolver: zodResolver(passwordSchema),
defaultValues: { password: "", confirmPassword: "" },
});
return (
<form onSubmit={handleSubmit((values) => console.log(values))} noValidate>
<label htmlFor="password">Password</label>
<input
id="password"
type="password"
{...register("password", { deps: ["confirmPassword"] })}
/>
{errors.password && <p role="alert">{errors.password.message}</p>}
<label htmlFor="confirmPassword">Confirm password</label>
<input
id="confirmPassword"
type="password"
{...register("confirmPassword")}
/>
{errors.confirmPassword && (
<p role="alert">{errors.confirmPassword.message}</p>
)}
<button type="submit">Save</button>
</form>
);
}z.infer works on a refined schema, because refine does not change the data shape.
Stale errors and the deps option
With mode: "onChange" or "onBlur", React Hook Form runs the whole schema when a field changes, but it only updates the error for the field that changed. Suppose the user types a matching confirmation, then edits password. The confirmation is now wrong, but its error does not appear until that field is touched again.
The deps option in register("password", { deps: ["confirmPassword"] }) fixes this. When password is validated, React Hook Form also re-validates confirmPassword. You can call trigger("confirmPassword") by hand for the same effect in an event handler.
Several issues from one check: superRefine
A plain refine produces one issue. When one check can fail in more than one way, or needs different paths, use superRefine and add issues yourself.
import { z } from "zod";
const rangeSchema = z
.object({
start: z.string().min(1, "Start date is required"),
end: z.string().min(1, "End date is required"),
})
.superRefine((data, ctx) => {
if (data.start && data.end && data.end < data.start) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "End date must be on or after the start date",
path: ["end"],
});
}
});The comparison works here because ISO date strings (2026-12-02) sort in date order. For other formats, parse them first. Guarding with data.start && data.end avoids reporting a range error on top of "required" errors.
Gotchas
- Order of refine and shape methods. In Zod 3,
.refine()returns a wrapped schema, so methods like.extend(),.pick()and.omit()are not available afterward. Call them first and add the refine last. Zod 4 keeps the object methods, but the habit is still safe. - Async checks. A refine with an async function forces async parsing.
zodResolverhandles this, but the check runs on every validation pass, so do not call an API from it on every keystroke. Keep schema rules pure and usesetErrorfor server checks. - Error placement. The message you see depends entirely on
path. If an error "vanishes", logerrorsand look for it under the root.
Summary
Use refine on the object for rules that compare fields, set path to the field that should show the error, and use superRefine when one check can raise several issues. Add deps to register so dependent fields stay current under onChange and onBlur modes.
Exercise
A start/end date form uses an object-level refine without a path option. The end date is earlier than the start date, and the user presses submit. The form does not submit, but no message appears next to either input. Why, and what is the fix?
Show answer
The issue has an empty path, so zodResolver places it on the root of formState.errors instead of errors.end. The inputs check errors.start and errors.end and never see it. Fix it by adding path: ["end"] to the refine options so the error appears at errors.end. Also set defaultValues for both fields so the refine runs.
Exercise
With mode: "onChange", a user fills in a matching password and confirmation, then edits the password. The confirmation field still shows no error even though the values now differ. How do you make it update?
Show answer
React Hook Form only updates the error of the field that changed. Add deps to the password registration, register("password", { deps: ["confirmPassword"] }), or call trigger("confirmPassword") in a change handler. Either one re-validates the confirmation field.