繁体   English   中英

是的日期验证 - 开始日期不能与结束日期相同

[英]yup date validation - Start Date must not be same as end date

我目前停留在如何使用 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"
          ),
})

但它不检查同一日期。 我很清楚这个线程: Date range validation - Start Date must not be same as End Date in jquense / yup ,但它尚未解决并使用 momentjs。 我公司在这个项目中严格使用 dayjs。

我希望你能帮助我解决使用 JS 或 dayjs 的问题。

谢谢 !

这是一个对我有用的解决方案。


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

你可以使用这个:

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(start_time.getTime() + 86400000);
                              
                                    return schema.min(dayAfter, 'End date has to be more than start date');
                                  }
                              
                                  return schema;
                                
                            }),
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM