如何验证Yup的开始日期是否晚于结束日期?

时间:2019-11-11 23:44:13

标签: reactjs material-ui formik yup

我有一个使用Formik库创建事件的表单。我需要检查开始日期是否与结束日期重叠,反之亦然。我有两个日期选择器来选择日期和时间。如何使用Yup验证这一点并在重叠时显示错误消息?

非常感谢您的帮助

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 个答案:

答案 0 :(得分:6)

使用ref效果很好

yup.object().shape({
              startDate: date(),
              endDate: date().min(
                  yup.ref('startDate'),
                  "end date can't be before start date"
                )
            }); 

答案 1 :(得分:4)

您可以使用when条件:

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

答案 2 :(得分:0)

纳德的回答对我有用。 但是我还有一些其他的验证条件,如果选中了复选框,则在结束日期之前验证日期开始日期。因此,我想出了这段代码。离开,以防将来有人需要

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(),
})

无条件

Yup.object().shape({
              StartDate: Yup.date(),
              EndDate: Yup.date().min(
                  Yup.ref('StartDate'),
                  "End date can't be before Start date"
                )
            });