1

I'm using Yup for my form validations in reactjs. My form has two dates, startDate and endDate. I have successfully implemented range validation. but in my scenario startDate must be grater than endDate (should not be equal). but schema below only checks for less than scenario for endDate. where as it accept same dates. Please help.

schema I'm using is:

schema = Yup.object().shape({
    startDate: Yup.date().min(new Date(), 'Please choose future date').typeError('Start Date is Required'),
    endDate: Yup.date().min(Yup.ref('startDate'), 'End date must be grater than start date').typeError('End Date is Required'),
});
Faisal Janjua
  • 703
  • 1
  • 8
  • 15

1 Answers1

1

I know it's too late but I'm posting this answer, I found this solutions if it can help :

    schema = Yup.object().shape({ 
          startDate: yup
            .date()
            .required("Start Date is Required"),
          endDate: yup
            .date()
            .min(
              yup.ref("startDate"),
              "End date must be grater than start date"
            )
            .test({
              name: "same",
              exclusive: false,
              params: {},
              message: "End date must be grater than start date",
              test: function(value) {
                const startDate = moment(this.parent.startDate).format("YYYY-MM-DD")
                const endDate = moment(value).format("YYYY-MM-DD")
                return !moment(startDate).isSame(moment(endDate))
              },
            }),
});
Connell.O'Donnell
  • 3,603
  • 11
  • 27
  • 61
Hamza
  • 29
  • 5
  • 1
    I haven't test the above code yet but It seems that it depends on another third-party library `moment` which I'll not appreciate. we can do same with native javascript Date method. – Faisal Janjua Feb 22 '21 at 19:16