英文:
React hook form and zod inumber input
问题
我使用React Hook Form创建了一个表单,并使用Zod进行了验证。在一个输入框中,我想输入数字,但当我输入任何数字时,错误消息显示它不是数字:
<Controller
name="calories"
control={control}
defaultValue={1}
render={({ field }) => (
<input
{...field}
type="number"
className="w-full px-3 py-2 border rounded-md"
/>
)}
calories: z
.number({
required_error: "卡路里是必填项",
invalid_type_error: "卡路里必须是数字",
})
.int()
.positive()
.min(1, { message: "卡路里至少应为1" }),
我是否漏掉了什么?
未找到解决方法。
英文:
I have created a form with react hook form and did a validation with zod. In one input I want to write in numbers, when I write any number, the error says it is not a number:
<Controller
name="calories"
control={control}
defaultValue={1}
render={({ field }) => (
<input
{...field}
type="number"
className="w-full px-3 py-2 border rounded-md"
/>
)}
calories: z
.number({
required_error: "Calories is required",
invalid_type_error: "Calories must be a number",
})
.int()
.positive()
.min(1, { message: "Calories should be at least 1" }),
I am missing something?
Did not find any solution to this
答案1
得分: 0
当输入的类型为number
时,即使用户输入数字,它也会将其值发送为string
。结果,Zod将该值视为string
并认为它无效,不符合number()
验证。
我不熟悉Zod,但这里的想法是,在应用Zod验证之前,如果可以的话,您需要将输入值转换为数字,否则将其验证为一个应该是有效数字的字符串,可以参考这里。
英文:
When the input is of type number
, it sends its value as a string
even if the user inputs a number.<br> As a result, Zod sees the value as a string
and considers it invalid for the number()
validation.
I am not familiar with Zod but the idea here is that before applying the Zod validation, if you can, you'll need to convert the input value to a number otherwise validate it as a string that should be a valid number have a look here
答案2
得分: 0
我找到了来自Ahmed Sbai的解决方案,在这里
最终解决方案如下:
calories: z.preprocess(
(a) => parseInt(z.string().parse(a), 10),
z.number().positive().min(1)
),
英文:
I found the solution that was given from Ahmed Sbai from here
End solution is this:
calories: z.preprocess(
(a) => parseInt(z.string().parse(a), 10),
z.number().positive().min(1)
),
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论