English 中文(简体)
React Hook Form and Zod:“invalid_type_error” 信号显示器不是“需要”
原标题:React Hook Form and Zod: "invalid_type_error" Message Displayed Instead of "required_error"

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.

问题回答

问题是,空投现场将提交NNN表格,由Zod解释为类型不匹配。 我猜想,你可以把你 Sch子看上去。

const Schema = z.object({
  age: z.number({
    invalid_type_error: "Age required",
  }),
});

这将提供更敏感的错误信息。 否则,你会向“反应照相”的制定者提出问题。

www.un.org/Depts/DGACM/index_french.htm 以超文本形式退还的价值为string。 为了将其转化为数目,您可使用Zod s .coerce(营运人。 查阅

如果你将你的外地价值类型定义为<代码>>> 编号但通过<编码> > > > 载明作为缺省外地价值,将会出现一个类型错误。 为处理这种情况,您可将数值类别<代码>nullable和null<>/code>作为缺省外地数值。

另一种选择是使用setValueAs。 React Hook Form register methods options to address the field Value Transformation.





相关问题
How to use one react app into another react app?

I have two react apps, parent app and child app. and child app have an hash router. I have build the child app using npm run build, It creates build folder. That build folder moved into inside the ...

how to get selected value in Ant Design

I want to print the selected value, and below is my option list: const vesselName = [ { value: 0 , label: ALBIDDA , }, { value: 1 , label: ALRUMEILA , }, { value: 2 ,...

How to add a <br> tag in reactjs between two strings?

I am using react. I want to add a line break <br> between strings No results and Please try another search term. . I have tried No results.<br>Please try another search term. but ...