I am using Formik + Yup for form creation with validation. I have following initial value.
const initialValue = {
title: '',
schedules: [
{
maxGame: '',
bookingDuration: [],
reservationSlots: [
{
from: null,
to: null,
increment: '',
pricePerHours: [
{
guest: '',
price: ''
}
],
pricePerGame: [
{
type: 'Child',
price: ''
}
]
}
]
}
]
};
My current yup schema:
const schema = {Yup.object().shape({
title: Yup.string()
.min(2, 'Must be 2 characters or more')
.required('Title is required'),
schedules: Yup.array().of(
Yup.object().shape({
bookingDuration: Yup.array().when('maxGame', {
is: '',
then: Yup.array().min(1, 'Booking Duration is required'),
otherwise: Yup.array()
}),
maxGame: Yup.number().when('bookingDuration', {
is: (bookingDuration) => bookingDuration.length === 0,
then: Yup.number()
.min(1, 'Max Game must be greater than zero')
.required('Max Game is required either fill booking duration'),
otherwise: Yup.number()
}),
reservationSlots: Yup.array().of(
Yup.object().shape({
from: Yup.date().typeError('Invalid Time'),
to: Yup.date().typeError('Invalid Time'),
increment: Yup.string().required('Time Increment is required'),
pricePerGame: Yup.array().of(
Yup.object().shape({
type: Yup.string(),
price: Yup.string()
.when(['type'], {
is: (type) => type,
then: Yup.string().required('Price is required'),
}),
})
),
},
)
},
[['bookingDuration', 'maxGame']])
)
})
}
I want following validation:
- Either one of bookingDuration and maxGame is required.
- If bookingDuration.length > 0 then price of pricePerHours should be required.
- If price of pricePerHours is filled then bookingDuration should be required.
- If maxGame !== '' then price of pricePerGame should be required.
- If price of pricePerGame is filled then maxGame should be required.
I am able to apply no. 1 validation but for rest unable to apply validation. Can you please help me on this.