0
votes

I have a ScheduleForm that has nested values called hours_attributes. The individual hours have a binding conditional where the presence of the opens value is required if the all_day value is false. Here's how my current schema is written:

const ScheduleSchema = Yup.object().shape({
  name: Yup.string()
    .required('Required'),
  hours_attributes: Yup.array().of(
    Yup.object().shape({
      opens: Yup.object().when('all_day', {
      is: false,
      then: Yup.string().required('Required'),
      otherwise: Yup.string()
    }),
  }))
});

I'm not sure if the when value is expecting the index of that particular hour's all_day value. Do I need some sort of index?

1

1 Answers

0
votes

Try by giving a function to 2nd argument of when:

const ScheduleSchema = Yup.object().shape({
  name: Yup.string()
    .required('Required'),
  hours_attributes: Yup.array().of(
    Yup.object().shape({
      opens: Yup.boolean().when('all_day', (value, schema) =>
        value ? schema : schema.required('Required')),
  }))
});

If above snippet doesn’t work then change hours_attributes like:


Yup.object({
      opens: Yup.boolean().when('all_day', (value, schema) =>
        value ? schema : schema.required('Required'))
}),

If you want value of opens to be true then:


Yup.object({
      opens: Yup.boolean().when('all_day', (value, schema) =>
        value ? schema : schema.oneOf([true], 'Required'))
}),