In the schema I would like to adjust the schema based on the sibling of the parent.
If for example: if toggleMonday is true, then weekdays -> monday should have a specific validation schema.
Now the following example works. However, it is quite verbose.
const schema = yup.object().shape({
toggleMonday: yup.bool().required(),
toggleTuesday: yup.bool().required(),
toggleWednesday: yup.bool().required(),
toggleThursday: yup.bool().required(),
toggleFriday: yup.bool().required(),
toggleSaturday: yup.bool().required(),
toggleSunday: yup.bool().required(),
weekdays: yup.object()
// works, toggleMonday is a sibling of weekdays
.when('toggleMonday', {
is: true,
then: yup.object().shape({
monday: yup.array().of(yup.object().shape(daySchema)).daySchemaFirstTimeslotRequired(),
tuesday: yup.array().of(yup.object().shape(daySchema)),
wednesday: yup.array().of(yup.object().shape(daySchema)),
thursday: yup.array().of(yup.object().shape(daySchema)),
friday: yup.array().of(yup.object().shape(daySchema)),
saturday: yup.array().of(yup.object().shape(daySchema)),
sunday: yup.array().of(yup.object().shape(daySchema)),
}),
})
.when('toggleTuesday', {
is: true,
then: yup.object().shape({
monday: yup.array().of(yup.object().shape(daySchema)),
tuesday: yup.array().of(yup.object().shape(daySchema)).daySchemaFirstTimeslotRequired(),
wednesday: yup.array().of(yup.object().shape(daySchema)),
thursday: yup.array().of(yup.object().shape(daySchema)),
friday: yup.array().of(yup.object().shape(daySchema)),
saturday: yup.array().of(yup.object().shape(daySchema)),
sunday: yup.array().of(yup.object().shape(daySchema)),
}),
})
// etc.
});
As you can see it is pretty repetitive.
The the mixed.when() method is used in this example. However it seems that you can only target sibling or sibling children fields.
Nesting it under each day respectively does not work since the days are nested in 'weekdays'.
Something in the lines of:
const schema = yup.object().shape({
toggleMonday: yup.bool().required(),
toggleTuesday: yup.bool().required(),
toggleWednesday: yup.bool().required(),
toggleThursday: yup.bool().required(),
toggleFriday: yup.bool().required(),
toggleSaturday: yup.bool().required(),
toggleSunday: yup.bool().required(),
weekdays: yup.object()
// does not work, toggleMonday is not a sibling of 'monday'
monday: yup.array().when('toggleMonday', {
is: true,
then: yup.array().of(yup.object().shape(daySchema)).daySchemaFirstTimeslotRequired(),
otherwise: yup.array().of(yup.object().shape(daySchema)),
}),
tuesday: yup.array().when('toggleMonday', {
is: true,
then: yup.array().of(yup.object().shape(daySchema)).daySchemaFirstTimeslotRequired(),
otherwise: yup.array().of(yup.object().shape(daySchema)),
}),
// etc.
});
Any advice?