Reputation: 4057
I am using Formik
and yup
for its validation.
I have the following requirements for validation of two fields started
and ended
started
must be a valid date.started
must be a past date.ended
can be null, means it is not required.ended
must not be null and must be a valid date if the started
has a valid date value.This is my validation schema:
validationSchema={yup.object().shape({
started: yup.date().max(new Date(), "Future date not allowed").typeError("Invalid Started date"),
ended: yup.date().default(null).when("started", {
is: yup.date().isValid(),
then: yup.date().min(yup.ref("started"), "Ended date must be later than Start date"),
otherwise: yup.date().nullable()
}).typeError("Invalid Ended date")
})}
1,2,3 are working, but the 4th validation is not working.
I also tried changing it to is: started => started !==null
, this is completely wrong because I console.log(started)
and that printed me Invalid date
.
I even tried is: true
that also didn't work.
What would be the correct way of validating this requirement?
Upvotes: 7
Views: 20137
Reputation: 151
Got this solution from here https://stackoverflow.com/a/60277510.
But basically this will check that started exists and then check if end time is later:
ended: yup.date().default(null)
.when("started",
(started, yup) => started && yup.min(started, "End time cannot be before start time"))
Upvotes: 13