ReactJS中如何为Zod对象Schema设置自定义错误信息?
为Zod对象Schema设置自定义必填错误信息
Zod的z.object().required()方法仅用于标记该字段为必填(不允许为undefined),并不支持直接传入自定义错误字符串。要给对象字段的必填校验设置自定义提示,需要使用refine方法实现:
方法一:校验对象是否为undefined
适用于仅禁止undefined的场景:
sub_facility: z .object({ id: z.number(), facility_name: z.string(), depth: z.number(), parentId: z.number().optional().nullable(), matchTerms: z.string().array(), }) .refine((val) => val !== undefined, { message: "Facility please", path: ["sub_facility"], // 指定错误路径,确保react-hook-form能正确关联到该字段 }),
方法二:同时禁止undefined和null
如果字段可能被设置为null,需要同时校验两种情况:
sub_facility: z .object({ id: z.number(), facility_name: z.string(), depth: z.number(), parentId: z.number().optional().nullable(), matchTerms: z.string().array(), }) .refine((val) => val !== undefined && val !== null, { message: "Facility please", path: ["sub_facility"], }),
注意事项
- 使用
refine时必须指定path,否则错误信息不会关联到sub_facility字段,而是被归类到表单的根错误中。 - 配合
react-hook-form的zodResolver使用时,自定义错误会正常出现在表单的errors对象中,可直接用于页面提示。
内容的提问来源于stack exchange,提问作者Anish Shrestha
相关产品推荐
相关产品推荐

