reactjs React hook form和zod inumber input

pftdvrlh  于 9个月前  发布在  React
关注(0)|答案(4)|浏览(98)

我用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"
            />
          )}

个字符
我错过了什么?
对此没有找到任何解决办法

5rgfhyps

5rgfhyps1#

我找到了来自here的Ahmed Sbai给出的解决方案。

calories: z.preprocess(
(a) => parseInt(z.string().parse(a), 10),
z.number().positive().min(1)
),

字符串

t40tm48m

t40tm48m2#

使用react-hook-form可以将字符串值转换为数字,如下所示:

<input
      {...register('numberInput', {
        setValueAs: (value) => Number(value),
      })}
      type="number"
    />

字符串

41zrol4v

41zrol4v3#

当输入类型为number时,即使用户输入数字,它也会将其值作为string发送。
因此,Zod将该值视为string,并认为它对于number()验证无效。
我不熟悉Zod,但这里的想法是,在应用Zod验证之前,如果可以的话,您需要将输入值转换为数字,否则将其验证为应该是有效数字的字符串。

bakd9h0s

bakd9h0s4#

你想要的是:

calories: z.coerce
    .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" }),

字符串
注意.number()之前的coerce。它将接受任何输入,即:数字'42'的字符串,并将其转换为数字42

相关问题