Here's an example of enforcing a datepicker's end date being after
the start date:
const schema = Yup.object().shape({
start_date: Yup.date()
.typeError('Start Date is required')
.required('Start Date is required'),
end_date: Yup.date()
.typeError('End Date is required')
.required('End Date is required')
.when('start_date', (start_date) => {
if (start_date) {
return Yup.date()
.min(start_date, 'End Date must be after Start Date')
.typeError('End Date is required')
}
}),
})
It was required to put the if
statement to validate correctly while the form was loading, and it was also required to put the typeError
rule in to validate correctly when the start date was selected but the end date wasn't yet.
The important thing is you can see usage of when
; the first param is the field to check against, and the second param is the validation function which returns a Yup validation object.
I tried to just return true or false, but it seemed to throw errors, so it's a bit more complex than it just being a pure validation function.