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
Advertisement
Answer
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