Hi there I’m using Yup as a validator for one of my schemas
This is my code here for validating schema
JavaScript
x
8
1
start: Yup.date()
2
.max(new Date(), "Max date")
3
.min(
4
new Date(new Date().setFullYear(new Date().getFullYear() - 120)),
5
"Min date")
6
),
7
end: Yup.date().min(Yup.ref('start'), "End date shouldn't be same as start date"),
8
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
JavaScript
1
19
19
1
const validationSearch = Yup.object().shape({
2
start: Yup.date()
3
.max(new Date(), "Max date")
4
.min(
5
new Date(new Date().setFullYear(new Date().getFullYear() - 120)),
6
"Min date"
7
),
8
9
end: Yup.date()
10
// .min(Yup.ref("start"), "End date shouldn't be same as start date")
11
.when("start", (val, schema) => {
12
if (val) {
13
const startDate = new Date(val);
14
startDate.setDate(startDate.getDate() + 1);
15
return val && schema.min(startDate, "Should beGreater than start date");
16
}
17
})
18
});
19
Please find sample codesandbox here