Schema Based Validation
- Popular libraries
- Install zod
npm i zod@3.20.6
import {z} from "zod";
const schema = z.object({
name: z.string().min(3, {message: "Name must be at least 3 chars"}),
age: z.number({invalid_type_error: "Age is required"}).min(18, {message: "Age must be at least 18"})
})
type FormData = z.infer<typeof schema>;
npm i @hookform/resolvers@2.9.11
import {zodResolver} from "@hookform/resolvers/zod";
- Pass schema to react hook form using zod resolver
useForm<FormData>({resolver: zodResolver(schema)});
register("name")
register("age", {valueAsNumber: true})
{errors.name && <p>{errors.name.message}</p> }