sgck
sgck

Reputation: 151

How to make end date at most one day after start date in Yup validation?

Currently, I have a yup schema to ensure that the end_time is at least after the start_time

    start_time: yup
        .date()
        .min(new Date(), 'Start datetime cannot be in the past')
        .required('Start datetime is required'),
    end_time: yup
        .date()
        .min(yup.ref('start_time'), 'End datetime must be after start datetime')
        .required('End datetime is required'),

I want to make it so that the end_time is at most 1day/24hrs after the start_time. For example, if the start_time is "Mon Apr 11 2022 18:30:00", I want the end_time to be at most "Tue Apr 12 2022 18:30:00". I would think of using .when() or .max(), but I am not sure of the format of how to begin.

Upvotes: 1

Views: 3094

Answers (1)

sgck
sgck

Reputation: 151

For anyone that runs into a similar issue, I have managed to solve the issue using the .when() method on the Schema object

    start_time: yup
        .date()
        .min(new Date(), 'Start datetime cannot be in the past')
        .required('Start datetime is required'),
    end_time: yup
        .date()
        .when('start_time', (start_time, schema) => {
            if (start_time) {
                const currentDay = new Date(start_time.getTime());
                const nextDay = new Date(start_time.getTime() + 86400000);
                return schema
                    .min(currentDay, 'End time must be after start time')
                    .max(nextDay, 'End time cannot be more than 24 hours after start time');
            } else {
                return schema;
            }
        })
        .required('End datetime is required'),

Upvotes: 3

Related Questions