51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

React Hook Form 和 Zod 中的数字输入

英文:

React hook form and zod inumber input

问题 {#heading}

我使用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:

&lt;Controller
          name=&quot;calories&quot;
          control={control}
          defaultValue={1}
          render={({ field }) =&gt; (
            &lt;input
              {...field}
              type=&quot;number&quot;
              className=&quot;w-full px-3 py-2 border rounded-md&quot;
            /&gt;
          )}

 calories: z
    .number({
      required_error: &quot;Calories is required&quot;,
      invalid_type_error: &quot;Calories must be a number&quot;,
    })
    .int()
    .positive()
    .min(1, { message: &quot;Calories should be at least 1&quot; }),

I am missing something?

Did not find any solution to this

答案1 {#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 {#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) =&gt; parseInt(z.string().parse(a), 10),
z.number().positive().min(1)
),

赞(0)
未经允许不得转载:工具盒子 » React Hook Form 和 Zod 中的数字输入