一年的开始和结束日期应该不同



嗨,我正在使用Yup作为我的一个模式的验证器

这是我在这里验证模式的代码

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"),

这是有效的,但我可以为开始日期和结束日期添加相同的日期。

我希望结束日期不同于的开始日期

非常感谢

您可以尝试Yup.何时处理此问题,

它为您提供了一个触发器,在该触发器上应该重新应用模式的字段更改以及用于处理验证的模式对象

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");
}
})
});

请在这里找到示例代码沙盒

这可以通过使用notOneOf来实现,如下所示:

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
});

不幸的是,moreThan不适用于日期,因此我们需要创建两个独立的检查器:end>=开始(分钟(,结束!==start(notOneOf(。

最新更新