简体   繁体   English

使用 Yup 和 Formik 对嵌套对象进行反应表单验证无法正常工作

[英]React form validation with Yup and Formik for nested object is not working properly

I have a form with nested object something like this,我有一个像这样的嵌套对象的表单,

const schema = Yup.object().shape({
  // ...
  isMultiDestination: Yup.boolean(),
  dropOffDestination1: Yup.object().shape({
    place_id: Yup.string().when("isMultiDestination", {
      is: true,
      then: Yup.string().required("Please enter destinaton 1")
    })
  }),
  dropOffDestination2: Yup.object().shape({
    place_id: Yup.string().when("isMultiDestination", {
      is: true,
      then: Yup.string().required("Please enter destinaton 2")
    })
  })
  // ...
});

const detailsForm = useFormik({
  validateOnBlur: true,
  validateOnChange: true,

  initialValues: {
    // ...
    isMultiDestination: false,
    dropOffDestination1: initPlaceObject,
    dropOffDestination2: initPlaceObject
    // ...
  },
  validationSchema: schema
});

After toggling the value of isMultiDestination and validating the form, the errors are not updated.切换isMultiDestination的值并验证表单后,错误不会更新。

Validation is failing.验证失败。

尝试像这样设置validationSchema:

validationSchema: yup.object().shape({ yourValidationSchema }),

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM