【问题标题】:yup date validation - Start Date must not be same as end date是的日期验证 - 开始日期不能与结束日期相同
【发布时间】:2021-12-27 06:57:24
【问题描述】:

我目前被困在如何在同一日期使用 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 的问题。

谢谢!

【问题讨论】:

    标签: javascript validation yup dayjs


    【解决方案1】:

    你可以用这个:

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

    【讨论】:

      猜你喜欢
      • 2020-12-27
      • 2022-01-06
      • 1970-01-01
      • 2015-09-29
      • 1970-01-01
      • 1970-01-01
      • 2020-07-13
      • 1970-01-01
      • 2018-01-31
      相关资源
      最近更新 更多