Sub topic 7
Connecting Zod to the form with zodResolver
This chapter assumes you can write React function components with hooks and read basic TypeScript generics. You should also know the useForm, register, and handleSubmit basics from earlier chapters, and how z.object and z.infer work. By the end, you will know what zodResolver does on each validation run, what the form receives back, and which mistakes produce confusing behavior.
What a resolver is
React Hook Form can validate in two ways. The first is rules passed to register, such as register("email", { required: true }). The second is a resolver, a function you pass to useForm. The resolver receives all current form values and returns either cleaned values or a map of errors.
zodResolver comes from the @hookform/resolvers package. It wraps a Zod schema in the shape React Hook Form expects. Install the packages together:
npm install react-hook-form zod @hookform/resolversThen pass the resolver to useForm:
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
const signUpSchema = z.object({
email: z.string().min(1, "Email is required").email("Enter a valid email"),
password: z.string().min(8, "Use at least 8 characters"),
});
type SignUpValues = z.infer<typeof signUpSchema>;
export function SignUpForm(),
handleSubmit,
formState: { errors, isSubmitting },
} = useForm<SignUpValues>({
resolver: zodResolver(signUaultValues: { email: "", password: "" },
});
const onSubmit = async (values: SignUpValues) => {
await fetch("/api/sign-up", {
headers: { "Content-Type": "application/json" },
body: JSON.stringify(values),
});
};
return (
<form onSubmit={handleSubmit(onSubmit)} noValidate>
<label htmlFor="email">Email</label>
<input id="email" type="email" {...register("email")} />
{errors.email && <p role="alert">{errors.email.message}</p>}
<label htmlFor="password">Password</label>
<input id="password" type="password" {...register("password")} />
{errors.password && <p rolepassword.message}</p>}
<button type="submit" disabled={isSubmitting}>
Create account
</button>
</form>
);
}The sch the only place the rules live. The register calls take no options, and the type argument to useForm comes from the schema.
What happens when validation runs
When validation is triggered, React Hook Form calls the resolver with the current values of every registered field. The resolver then follows these steps:
- It runs
schema.safeParseAsync(values), or the equivalent for your Zod version. This is an async parse that never throws on invalid data. - If parsing succeeds, it returns the parsed data as
valuesand an emptyerrorsobject. - If parsing fails, it converts each Zod issue into a React Hook Form error. The issue's
pathbecomes the field name, so["items", 0, "name"]becomesitems.0.name. - React Hook Form stores the result in
formState.errors, and components reading that state re-render.
The sequence has two consequences:
- Your submit callback only runs with valid data. If the schema fails,
handleSubmitnever callsonSubmit. It stores the errors and focuses the first invalid field. - The callback receives parsed data, not raw input. If the schema transforms, trims, or strips values,
onSubmitsees the result. By defaultz.objectdrops keys it does not know about, so extra form values will not reach your API.
One error per field
A single field can fail several rules at once. For example, "ab" might fail both a length rule and a regex rule. By default, React Hook Form keeps only the first issue for each field in errors.field.message. That behavior is controlled by the criteriaMode option, which defaults to "firstError".
If you want every failing rule, set criteriaMode: "all". The extra messages then appear in errors.field.types, keyed by the Zod issue code.
const { register, formState: { errors } } = useForm<SignUpValues>({
resolver: zodResolver(signUpSchema),
criteriaMode: "all",
});
// errors.password?.types might look like { too_small: "Use at least 8 characters" }Most forms are better off with the default. Showing one message at a time is easier to read and easier for screen readers to announce.
Rules that move out of register
Once a resolver is set, React Hook Form uses it instead of the validation rules passed to register. If you write register("email", { required: true }) next to a resolver, that rule is not what decides validity. Keep every rule in the schema, and keep register for wiring only.
HTML attributes behave differently. An attribute like required or minLength on an <input> can still trigger the browser's own validation and its pop-up messages before React Hook Form runs. Add noValidate to the <form> element, as the example above does, so the schema is the single source of truth.
Empty inputs are strings, not undefined
A text input that the user never touched holds "", not undefined. This causes the most common first bug with Zod. z.string() accepts "", so a "required" field passes unless you say otherwise. Add .min(1, "Email is required"), as the schema above does.
Number inputs have a similar trap. register returns strings by default, so z.number() fails with "expected number, received string". You have two fixes:
- Add
valueAsNumber: trueto the field:register("age", { valueAsNumber: true }). An empty field then becomesNaN, which Zod reports as invalid. - Keep the input as a string in the schema and convert it with
.transform(Number). A later chapter covers this in the section on input and output types.
Cross-field rules and where errors land
The resolver validates the whole object, so a rule that compares fields works. The path you give to refine decides which field shows the error.
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"],
});Without path, the issue has an empty path and does not attach to errors.confirmPassword. The input would show nothing.
There is also an ordering catch. Zod runs refine on an object only after every field in the object passes its own checks. If password is too short, the "Passwords do not match" error does not appear yet. It shows up once the field rules are satisfied, which is expected but surprises people during testing.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Required field submits empty | `z.string()` accepts `""` | Add `.min(1, "message")` |
| `expected number, received string` | Input values are strings | Use `valueAsNumber` or a transform |
| Cross-field error never shows | `refine` has no `path`, or field rules still fail | Set `path`, and fix field errors first |
| Browser pop-up appears instead of your message | HTML validation is active | Add `noValidate` to the form |
| Rules in `register` seem ignored | The resolver takes over validation | Move the rules into the schema |
| Type error on `useForm` with transforms | Input and output types differ | Use three type arguments (next chapters) |
Changing when the resolver runs
The resolver runs when the validation mode says so. The default mode is onSubmit, and after the first submit the form re-validates on each change. You can switch modes with mode: "onBlur" or mode: "onChange" in useForm. The resolver still validates the entire object each time, but React Hook Form only updates the errors for fields that fit the current trigger. The next chapter covers the modes in detail.
Exercise
A form uses zodResolver with a schema where username is z.string(). The user leaves the field empty and submits. The form submits successfully, but the server rejects the empty username. What is the cause, and what is the fix?
Show answer
An untouched text input holds an empty string, and z.string() accepts empty strings, so the schema passes. Change the rule to z.string().min(1, "Username is required"). Keep the rule in the schema rather than in register, because the resolver replaces register validation rules.
Exercise
You add .refine(...) to compare password and confirmPassword, but no message appears under the confirm input, even when the values differ. Name two possible causes.
Show answer
First, the refine call has no path: ["confirmPassword"], so the issue is not attached to that field. Second, another rule on the object is failing, such as a password that is too short. Zod skips the object-level refine until the field rules pass.