'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.

Validation is failing.



Solution 1:[1]

try to set validationSchema like this:

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ozan