I m currently working with react-hook-form and zod for form validation in my React project. I have a specific field, let s call it age, with its input type set to the default (string). In the Zod schema, I explicitly define this field as a number using z.number()
.
下面是我守则的简化版本:
const Schema = z.object({
age: z.number({
required_error: "Required",
invalid_type_error: "Invalid type",
}),
});
type SchemaType = z.infer<typeof Schema>;
const form = useForm<SchemaType>({
resolver: zodResolver(Schema),
});
预期的行为是,在提交表格时,在不输入年龄领域的任何内容时,它应当显示“要求”的信息。 然而,实际行为是显示“无效型”信息。
I m 采用z.infer<typeof Schema>
,以确保年龄领域的类型被正确地推断为人数。 是否有办法解决这一问题,并确保在无投入的情况下,“要求”的信息而不是“有效类型”的信息被展示?
然后,我要说几句不错的话。
Schema.parse({
age: 20
})
感谢你的援助!
Attempted Solution:
I defined a Zod schema with the age
field set to z.number()
in order to enforce that it should be a number. I used z.infer<>
to ensure the correct type. My form configuration uses react-hook-form
with the Zod resolver.
Expected Outcome:
I expected that when submitting the form without inputting anything into the age
field, the validation should trigger the "Required" message as specified in the Zod schema.
Actual Result: However, the issue I encountered is that upon submission without input, the form displays the "Invalid type" message instead of the expected "Required" message. I m seeking guidance on resolving this discrepancy.