Yup conditional schema without nested object

Viewed 14

OtherResonChage only required if ReasonChange array include "Other" in it else that field is not required

export const formikValues = {
  reasonChangeJob: [],
  otherReasonChangeJob: "",
}


export const questionnaireSchema = Yup.object({
  reasonChangeJob: Yup.array()
    .required("req")
    .min(1, "min q"),
  otherReasonChangeJob: Yup.string().when(
    "reasonChangeJob",
    (reasonChangeJob) => {
      if (reasonChangeJob.include("other")) {
        return Yup.string().required(" req");
      }
    }
  )
});
1 Answers

I'm using include instead of includes and this is the better way to handle conditional validations

  otherReasonChangeJob: Yup.string().when("reasonChangeJob", {
    is: (reasonChangeJob) => reasonChangeJob.includes("other"),
    then: Yup.string().required("Require please"),
  }),

Related