Validation
- React course
- Advanced
- Lesson 35/56
- 4 min
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.
Practice 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'.
Starter code
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
// Write ZodForm hereSample 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;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What connects a Zod model to react-hook-form?
- useState
- useEffect
- zodResolver Correct answer
- useMemo
Explanation: zodResolver connects the model to the form.
2 zodResolver usage
useForm({ resolver: ____(formDef) });
useForm({ resolver: zodResolver(formDef) });
Explanation: zodResolver connects the model.
3 Validation: match the terms
| Term | Meaning |
|---|---|
z.object |
Defines structure |
zodResolver |
Connects to form |
z.string |
Expects text |
z.email |
Validates email |