Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I validate if a start date is after an end date with Yup?

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>
    )

}
like image 499
QThompson Avatar asked Nov 11 '19 23:11

QThompson


People also ask

What is a date validation?

date of validation means the date when the Referred Party has successfully validated his/her identity and fully completed the on-boarding procedures.

How do I validate the end date and time?

Here's the fun bit - how to ensure that the end date and time as a whole is at least 1 hour or later than the start date and time. Starting with the end date, the validation is similar to the start date with the only difference being the addition of a minimum value (cannot be earlier than the start date).

How do I set up a Yup validation?

When setting up a yup validation it can work on a single value or an object. To validate an object we'd use the object import from yup like so import { object } from "yup"; Our validation schema would then be setup to mirror what the object structure will be to validate.

How do I use yup with a date string?

By default yup will pass the value to new Date () however depending on the format of your date string that may or may not work. If the way you're storing your date value doesn't work when passing to new Date () then you'll need to setup a custom transform. When setting up a yup validation it can work on a single value or an object.

Can the end date be earlier than the start date?

The end date cannot be earlier than the start date. If the end date equals the start date, the end time must be 1 hour or more after the start time. Upon submission of Form 1, the values for the fields are updated and stored in the Redux state.


2 Answers

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"
                )
            }); 
like image 152
Nader Magdi Mahfouz Avatar answered Sep 17 '22 08:09

Nader Magdi Mahfouz


You can use when condition:

eventStartDate: yup.date().default(() => new Date()),
eventEndDate: yup
        .date()
        .when(
            "eventStartDate",
            (eventStartDate, schema) => eventStartDate && schema.min(eventStartDate))
like image 27
sri Avatar answered Sep 17 '22 08:09

sri