Sky*_*zer 5 javascript validation yup dayjs
我目前陷入如何在同一日期使用 yup 进行验证的问题。
目前我可以使用以下方法验证 endDate 是否不在 startDate 之前:
schema = yup.object().shape({
startDate: yup.date().min(new Date(),'Please choose future date'),
endDate: yup
.date()
.min(
yup.ref("startDate"),
"End date has to be more than start date"
),
})
Run Code Online (Sandbox Code Playgroud)
但它不检查相同的日期。我很清楚这个线程: 日期范围验证 - 开始日期不得与jquense / yup中的结束日期相同,但尚未解决并使用momentjs。我的公司在这个项目中严格使用dayjs。
我希望你能帮助我使用 JS 或 dayjs 解决方案。
谢谢 !
你可以使用这个:
schema = yup.object().shape({
startDate: yup.date().min(new Date(),'Please choose future date'),
endDate: yup
.date()
.when('startDate',
(startDate, schema) => {
if (startDate) {
const dayAfter = new Date(startDate.getTime() + 86400000);
return schema.min(dayAfter, 'End date has to be after than start date');
}
return schema;
}),
})
Run Code Online (Sandbox Code Playgroud)
小智 6
这是一个对我有用的解决方案。
const validationSchema = Yup.object({
startDate: Yup.date().required(),
endDate: Yup.date().test(
"same_dates_test",
"Start and end dates must not be equal.",
function (value) {
const { startDate } = this.parent;
return value.getTime() !== startDate.getTime();
}
),
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13873 次 |
| 最近记录: |