React Hook Form 和 Zod 中的数字输入

huangapple go评论185阅读模式
英文:

React hook form and zod inumber input

问题

我使用React Hook Form创建了一个表单,并使用Zod进行了验证。在一个输入框中,我想输入数字,但当我输入任何数字时,错误消息显示它不是数字:

  1. <Controller
  2. name="calories"
  3. control={control}
  4. defaultValue={1}
  5. render={({ field }) => (
  6. <input
  7. {...field}
  8. type="number"
  9. className="w-full px-3 py-2 border rounded-md"
  10. />
  11. )}
  1. calories: z
  2. .number({
  3. required_error: "卡路里是必填项",
  4. invalid_type_error: "卡路里必须是数字",
  5. })
  6. .int()
  7. .positive()
  8. .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:

  1. &lt;Controller
  2. name=&quot;calories&quot;
  3. control={control}
  4. defaultValue={1}
  5. render={({ field }) =&gt; (
  6. &lt;input
  7. {...field}
  8. type=&quot;number&quot;
  9. className=&quot;w-full px-3 py-2 border rounded-md&quot;
  10. /&gt;
  11. )}
  1. calories: z
  2. .number({
  3. required_error: &quot;Calories is required&quot;,
  4. invalid_type_error: &quot;Calories must be a number&quot;,
  5. })
  6. .int()
  7. .positive()
  8. .min(1, { message: &quot;Calories should be at least 1&quot; }),

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的解决方案,在这里
最终解决方案如下:

  1. calories: z.preprocess(
  2. (a) => parseInt(z.string().parse(a), 10),
  3. z.number().positive().min(1)
  4. ),
英文:

I found the solution that was given from Ahmed Sbai from here
End solution is this:

  1. calories: z.preprocess(
  2. (a) =&gt; parseInt(z.string().parse(a), 10),
  3. z.number().positive().min(1)
  4. ),

huangapple
  • 本文由 发表于 2023年8月11日 03:03:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76878664.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定