start and end date should be different for one year

Viewed 125

Hi there I'm using Yup as a validator for one of my schemas

This is my code here for validating schema

            start: Yup.date()
                .max(new Date(), "Max date")
                .min(
                    new Date(new Date().setFullYear(new Date().getFullYear() - 120)),
                    "Min date")
                ),
            end: Yup.date().min(Yup.ref('start'), "End date shouldn't be same as start date"),

This works but I can add the same date for the start date and end date.

I want that end date to be different and higher than start date

Thanks a lot

2 Answers

You can try Yup.when to handle this,

It provides you a trigger on which field change the schema should be recomplied and schema object for handling validations

const validationSearch = Yup.object().shape({      
  start: Yup.date()
    .max(new Date(), "Max date")
    .min(
      new Date(new Date().setFullYear(new Date().getFullYear() - 120)),
      "Min date"
    ),

  end: Yup.date()
    // .min(Yup.ref("start"), "End date shouldn't be same as start date")
    .when("start", (val, schema) => {
      if (val) {
        const startDate = new Date(val);
        startDate.setDate(startDate.getDate() + 1);
        return val && schema.min(startDate, "Should beGreater than start date");
      }
    })
});

Please find sample codesandbox here

This can be achieved by using notOneOf, as shown below:

const Yup = require("yup");
const moment = require("moment");

const schema = Yup.object().shape({
    start: Yup.date()
        .max(new Date(), "Max date")
        .min(new Date(new Date().setFullYear(new Date().getFullYear() - 120)), "Min date"),
    end: Yup.date()
        .min(Yup.ref("start"), "End date should be higher than the start date")
        .notOneOf([Yup.ref("start"), null], "End date should not be the same as the start date")
});

  
const startDate = moment().subtract(1, "minute").toDate(); //This date has to be smaller than the Date declaration in start.max
const endDate = startDate;

schema.isValid({
    start: startDate,
    end: endDate
}).then((valid) => {
    console.log(valid); //False
});

Unfortunately, moreThan is not available for dates, so we need to create two separate checkers: end >= start (min), end !== start (notOneOf).

Related