在某些情况下,即使不应将表单值视为有效,看起来Formik的标志“ isValid”也设置为true
。我在下面展示了一个有效的codeandbox示例。
我用于表单的验证架构如下:
const validationSchema = Yup.object().shape(
{
heading: Yup.string().required('Heading required.'),
image: Yup.string().when('placeholder', {
is: '',
then: Yup.string().required(
'Please either choose an image, or a placeholder.'
),
otherwise: Yup.string(),
}),
placeholder: Yup.string().when('image', {
is: '',
then: Yup.string().required(
'Please either choose an image, or a placeholder.'
),
otherwise: Yup.string(),
}),
},
[['image', 'placeholder']]
);
输出Formik的isValid
标志时,以下值是true
:
{ heading: 'a', image: '', placeholder: '' }
该模式指出必须存在字段“图像”或“占位符”之一,但在上述情况下则不存在。但是isValid
标志是true
。
当用Yup手动测试时,我得到了预期的结果:
validationSchema.validate(values).then(...).catch(...);
这可以在codesandbox中进一步看到。我在这里想念什么? Formik验证值时,幕后还会发生更多事情吗?
答案 0 :(得分:1)
我也面临同样的问题,因此与 formik.isValid
一起,我使用了另一个属性 formik.touched
并认为该表单仅在 {{1 }} 和 formik.isValid = true
(至少应该触及某些字段) 如下:
Object.keys(formik.touched).length > 0