我用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"
/>
)}
个字符
我错过了什么?
对此没有找到任何解决办法
4条答案
按热度按时间5rgfhyps1#
我找到了来自here的Ahmed Sbai给出的解决方案。
字符串
t40tm48m2#
使用react-hook-form可以将字符串值转换为数字,如下所示:
字符串
41zrol4v3#
当输入类型为
number
时,即使用户输入数字,它也会将其值作为string
发送。因此,Zod将该值视为
string
,并认为它对于number()
验证无效。我不熟悉Zod,但这里的想法是,在应用Zod验证之前,如果可以的话,您需要将输入值转换为数字,否则将其验证为应该是有效数字的字符串。
bakd9h0s4#
你想要的是:
字符串
注意
.number()
之前的coerce
。它将接受任何输入,即:数字'42'的字符串,并将其转换为数字42
。