Formik-嵌套字段验证

时间:2019-10-10 09:08:44

标签: javascript reactjs formik yup

我有带有数字输入的嵌套字段,并且无法使验证正常工作。不知道这是formik还是yup问题/如何声明验证模式,但我将在这里开始提问。

在示例中,我有两个代表数字的字段,默认为空字符串。验证适用于第一个字段,但我无法使它对嵌套字段的行为相同。当我触摸该字段但不输入任何内容时,它会返回:

  

social.facebook必须为number类型,但最终值为:   NaN(从值""开始)。

示例:codesandbox

1 个答案:

答案 0 :(得分:2)

似乎是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()
    })
})}

请参见Augmented Images

为进一步验证,如果您只想输入特殊的数字,请添加ML Kit

如下:

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()
    })
})}

PS: 您可以将初始值设置为,将数字设置为null,然后将.nullable()添加到schenma中。