Sub topic 10
Cross-field rules with refine
This chapter assumes you can build a form with useForm, register, and zodResolver, and that you know how to define a Zod object schema. It covers rules that depend on more than one field, such as "confirm password must match password".
Why field rules are not enough
A rule like z.string().min(8) sees only one value. It cannot compare that value to another field. To compare fields, you attach a check to the whole object with refine.
refine takes a function that receives the parsed data and returns true when the data is valid. The second argument sets the error message and the path.
A password confirmation rule
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 path option decides where the error lands. Without it, the error is attached to the object root. React Hook Form would then store it under errors.root or not show it next to any input. With path: ["confirmPassword"], the message appears in errors.confirmPassword.message, so you render it like any other field error.
Common errors
- The refine never runs. Zod runs object-level refinements only when the field rules pass. If
passwordis too short, you will not see "Passwords do not match" until you fix it. This is expected, not a bug. - The error shows nowhere. You forgot
path, or the path does not match a registered field name. - A typo in
path. The path is an array of strings.["confirmPassword"]works, and"confirmPassword"does not.
Wiring it to a form
Nothing changes in the component. Pass the schema to zodResolver and read the error as usual:
const {
register,
handleSubmit,
formState: { errors },
} = useForm<z.infer<typeof passwordSchema>>({
resolver: zodResolver(passwordSchema),
defaultValues: { password: "", confirmPassword: "" },
});
// In the JSX:
// <input type="password" {...register("confirmPassword")} />
// {errors.confirmPassword && <p role="alert">{errors.confirmPassword.message}</p>}Several rules on one object
You can chain more than one refine. Each one gets its own message and path. Keep each rule small so the message matches the failure.
Exercise
A schema has password and confirmPassword, and a refine check without a path option. The passwords differ, but no message appears under the confirm input. Why, and how do you fix it?
Show answer
Without path, the error is attached to the object root instead of the confirmPassword field, so errors.confirmPassword is empty. Add path: ["confirmPassword"] to the refine options.