How do I validate if a start date is after an end date with Yup?
use ref
it works just fine
yup.object().shape({
startDate: date(),
endDate: date().min(
yup.ref('startDate'),
"end date can't be before start date"
)
});
Nader's answer worked for me. But I had some additional validation condition that if a checkbox is checked then validate the date start date before the end date. So, I came up with this code. leaving in case someone needs this in future
Yup.object.shape({
ServiceCheck: Yup.boolean().default(false),
StartDateTime: Yup.date().when('ServiceCheck', {
is: (ServiceCheck=> {
return (!!ServiceCheck) ? true : false;
}),
then: Yup.date().required('Start Date/Time is required')
}).nullable(),
EndDateTime: Yup.date().when('ServiceCheck', {
is: (ServiceCheck=> {
return (!!ServiceCheck) ? true : false;
}),
then: Yup.date().min(Yup.ref('StartDateTime'),
"End date can't be before Start date").required('End Date/Time is required')
}).nullable(),
})
without condition
Yup.object().shape({
StartDate: Yup.date(),
EndDate: Yup.date().min(
Yup.ref('StartDate'),
"End date can't be before Start date"
)
});
You can use when
condition:
eventStartDate: yup.date().default(() => new Date()),
eventEndDate: yup
.date()
.when(
"eventStartDate",
(eventStartDate, schema) => eventStartDate && schema.min(eventStartDate))