Validate a form with React Hook Form and Zod
Connect a Zod 4 schema to React Hook Form with zodResolver, so validation rules live in one schema and errors map to each field.
Validation written inside the component is hard to reuse. A Zod schema holds the rules, and the resolver feeds its errors to the form.
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
const schema = z.object({
email: z.email('Enter a valid email'),
age: z.coerce.number().min(18, 'Must be 18 or older'),
});
export function SignupForm() {
const {
register,
handleSubmit,
formState: { errors },
} = useForm({ resolver: zodResolver(schema) });
return (
<form onSubmit={handleSubmit((data) => console.log(data))}>
<input {...register('email')} />
<p>{errors.email?.message}</p>
<input type="number" {...register('age')} />
<p>{errors.age?.message}</p>
<button>Sign up</button>
</form>
);
}(submit with "nope" and 16) -> Enter a valid email / Must be 18 or older
(submit with [email protected] and 30)
{ email: '[email protected]', age: 30 }register connects an input and handleSubmit calls your function only when the schema passes. z.coerce.number() converts the string from the input to a number first. The resolver comes from @hookform/resolvers, and a version that supports Zod 4 is needed, as the resolver docs note.
Reuse the same schema on the server and parse the request body there, since client validation is only a convenience.