React-Hooks-Form 集成 Zod 校验库
首先需要安装 react hooks form
官方提交的解析器
npm install @hookform/resolvers
再安装校验库
npm install zod
它不仅支持 Zod
校验库同时还支持目前各种主流的校验库比如:Yup、Zod、Joi、Ajv、Vest、Custom
具体查看官方文档: https://react-hook-form.com/docs/useform#resolver
我们就拿 Zod 举例:
import { useState } from "react";
import { SubmitHandler, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod"
import * as z from "zod"// 定义校验参数
const schema = z.object({name: z.string().min(1, { message: "名称不能为空" }),age: z.number().min(1, { message: "年龄不能小于1" }).max(99, { message: "年龄不能超过99" }),
})type Schema = z.infer<typeof schema>export default () => {const [defaultValues, setDefaultValues] = useState<Schema>({ name: "", age: 0 })const { register, handleSubmit, formState: { errors } } = useForm<Schema>({// 默认值defaultValues,// 配置校验解析器resolver: zodResolver(schema),});const onSubmit: SubmitHandler<Schema> = (data, event) => {// 阻止默认提交行为event?.preventDefault();console.log(data)}return (<><form onSubmit={handleSubmit(onSubmit)}><input {...register("name")} type="text" /><span>{errors.name && errors.name.message}</span><input {...register("age")} type="text" /><span>{errors.age && errors.age.message}</span><button type="submit">提交</button></form></>)
}
详细的校验配置信息可查看 Zod
官方文档:https://zod.dev/