seb*_*rik 6 javascript reactjs yup formik
我有带有数字输入的嵌套字段,但无法使验证正常工作。不确定这是否是 formik 或 yup 的问题/验证模式是如何声明的,但我会在这里开始询问。
在示例中,我有两个字段代表数字,默认为空字符串。验证适用于第一个字段,但我无法使其对嵌套字段的行为相同。当我触摸该字段但不输入任何内容时,它会返回:
social.facebook 必须是一种
number类型,但最终值是:(NaN从值中转换"")。
示例:代码沙盒
似乎是 formik 的问题,嵌套字段验证!当它的数字和值用空字符串初始化时,最后抛出该错误
你可以通过在它是一个空字符串时转换为 null 来解决它,然后在validationSchema中将其设置为可空,如下所示
validationSchema={Yup.object().shape({
email: Yup.number(),
social: Yup.object().shape({
facebook: Yup.number()
.transform((value, originalValue) => originalValue.trim() === "" ? null: value)
.nullable()
})
})}
Run Code Online (Sandbox Code Playgroud)
查看代码沙盒
为了进一步验证,如果您只需要数字的特殊消息,请添加.typeError("your message")
如下 :
validationSchema={Yup.object().shape({
email: Yup.number().typeError("must be a number"),
social: Yup.object().shape({
facebook: Yup.number()
.typeError("must be a number")
.transform((value, originalValue) => originalValue.trim() === "" ? null: value)
.nullable()
})
})}
Run Code Online (Sandbox Code Playgroud)
PS:您可以将数字的初始值设置为 null 并将 .nullable() 添加到 schenma 。
| 归档时间: |
|
| 查看次数: |
4248 次 |
| 最近记录: |