The Coder
The Coder

Reputation: 4057

Yup: How to validate two dates which are dependent on each other?

I am using Formik and yup for its validation.
I have the following requirements for validation of two fields started and ended

  1. started must be a valid date.
  2. started must be a past date.
  3. ended can be null, means it is not required.
  4. 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

Answers (1)

LOPHER
LOPHER

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

Related Questions