18
votes

I have a form that creates an event using Formik library. I need to check to see if the start date overlaps the end date and vice-versa. I have two date pickers that choose the date and time. How can I use Yup to validate this and show an error message if they do overlap?

Thanks for the help in advance

const validationSchema = Yup.object().shape({
    eventName: Yup.string()
        .min(1, "Must have a character")
        .max(10, "Must be shorter than 255")
        .required("Must enter an event name"),

    email: Yup.string()
        .email("Must be a valid email address")
        .max(255, "Must be shorter than 255")
        .required("Must enter an email"),

    eventStartDate: Yup.date()
        .required("Must enter start date"),


    eventEndDate: Yup.date()
        .required("Must enter end date")


})

var defaultValue = new Date().toDateString


export default function EventForm(){

    return (
        <Formik 
        initialValues={{eventName: "", email: "", }}
        validationSchema={validationSchema}
        onSubmit={(values, {setSubmitting, resetForm}) => {
            setTimeout(() => {

        }}
        >
            { ({
                values, 
                errors, 
                touched, 
                handleChange, 
                handleBlur,
                handleSubmit,
                isSubmitting
            }) => (
                <form onSubmit={handleSubmit}>
                <div className="input-row">
                    <TextField
                        id="eventName"
                        label="Event Name"
                        margin="normal"
                        variant="filled"
                        onChange={handleChange}
                        onBlur={handleBlur}
                        value={values.eventName}
                        className={touched.eventName && errors.eventName ? "has-error" : null}
                        />
                    <Error touched={touched.eventName} message={errors.eventName}/>
                </div>

                <div className="dateHolder">
                    <div className="startDate">
                            <TextField 
                                id="eventStartDate"
                                label="Event Start Date"
                                type="datetime-local"
                                InputLabelProps={{
                                    shrink: true
                                }}
                                format="yyy-dd-mm HH:MM:ss"
                                onChange={handleChange}
                                onBlur={handleBlur}
                                value={values.eventStartDate}
                            />
                            <Error touched={touched.eventStartDate} message={errors.eventStartDate}/>
                    </div>

                    <div className="endDate">
                    <TextField 
                                id="eventEndDate"
                                label="Event End Date"
                                type="datetime-local"
                                InputLabelProps={{
                                    shrink: true
                                }}
                                format="yyy-dd-mm HH:MM:ss"
                                onChange={handleChange}
                                onBlur={handleBlur}
                                value={values.eventEndDate}
                            />
                            <Error touched={touched.eventEndDate} message={errors.eventEndDate}/>
                    </div>
                </div>


                <div className="input-row">
                <button type="submit" disabled={isSubmitting} >
                    Submit
                </button>
          </div>

            </form>
            )}
        </Formik>
    )

}
3

3 Answers

31
votes

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"
                )
            }); 
13
votes

You can use when condition:

eventStartDate: yup.date().default(() => new Date()),
eventEndDate: yup
        .date()
        .when(
            "startDate",
            (eventStartDate, schema) => eventStartDate && schema.min(eventStartDate))
5
votes

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"
                )
            });