React
Validation
Learn to validate a form with a Zod schema.
Validation definition with Zod
Zod is a TypeScript-friendly validation definition library. You define an object definition and validate data against it.
You connect Zod to react-hook-form with zodResolver. The call useForm({ resolver: zodResolver(formDef) }) delegates form validation to the definition.
This approach collects validation rules in a single definition; it simplifies form code and adds type safety.
Using zodResolver
First you define a Zod model: const formModel = z.object({ email: z.string().email() });. Then you connect it with useForm({ resolver: zodResolver(formModel) }).
From this point you do not need to write required in register calls; the model handles validation. Errors still appear in formState.errors.
Zod also auto-generates TypeScript types; this keeps the form data type always correct.
Exercise Write a form with Zod model
Complete the skeleton. Define const formModel = z.object({ email: z.string().email() });. Call useForm({ resolver: zodResolver(formModel) }). Inside <form onSubmit={handleSubmit(onSubmit)}> put <input {...register('email')} /> and <button type="submit">Submit</button>. Add export default. Import z from 'zod', zodResolver from '@hookform/resolvers/zod'.
Show example solution
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
const formModel = z.object({ email: z.string().email() });
function ZodForm() {
const { register, handleSubmit } = useForm({ resolver: zodResolver(formModel) });
return (
<form onSubmit={handleSubmit((data) => console.log(data))}>
<input {...register('email')} />
<button type="submit">Submit</button>
</form>
);
}
export default ZodForm;
Test yourself
-
What connects a Zod model to react-hook-form?
- useState
- useEffect
- zodResolver
- useMemo
Show answer
zodResolver — zodResolver connects the model to the form.
-
zodResolver usage
useForm({ resolver: ____(formDef) });
Show answer
useForm({ resolver: zodResolver(formDef) });
-
Validation: match the terms
- z.object
- Defines structure
- zodResolver
- Connects to form
- z.string
- Expects text
- z.email
- Validates email
Next lesson: Summary - react-hook-form