【问题标题】:Date range validation - Start Date must not be same as End Date in jquense / yup日期范围验证 - 开始日期不能与 jquense / yup 中的结束日期相同
【发布时间】:2020-12-27 15:34:50
【问题描述】:

我在 reactjs 中使用 Yup 进行表单验证。我的表格有两个日期,startDateendDate。我已成功实施范围验证。但在我的场景中 startDate 必须大于 endDate (不应该相等)。但下面的架构只检查 endDate 的场景。因为它接受相同的日期。请帮忙。

我使用的模式是:

schema = Yup.object().shape({
    startDate: Yup.date().min(new Date(), 'Please choose future date').typeError('Start Date is Required'),
    endDate: Yup.date().min(Yup.ref('startDate'), 'End date must be grater than start date').typeError('End Date is Required'),
});

【问题讨论】:

    标签: reactjs validation yup


    【解决方案1】:

    我知道为时已晚,但我发布了这个答案,如果有帮助,我找到了这个解决方案:

        schema = Yup.object().shape({ 
              startDate: yup
                .date()
                .required("Start Date is Required"),
              endDate: yup
                .date()
                .min(
                  yup.ref("startDate"),
                  "End date must be grater than start date"
                )
                .test({
                  name: "same",
                  exclusive: false,
                  params: {},
                  message: "End date must be grater than start date",
                  test: function(value) {
                    const startDate = moment(this.parent.startDate).format("YYYY-MM-DD")
                    const endDate = moment(value).format("YYYY-MM-DD")
                    return !moment(startDate).isSame(moment(endDate))
                  },
                }),
    });
    

    【讨论】:

    • 我还没有测试上面的代码,但它似乎依赖于另一个第三方库moment,我不会欣赏。我们可以用原生 javascript Date 方法做同样的事情。
    猜你喜欢
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 2020-03-07
    • 1970-01-01
    • 2015-09-29
    • 1970-01-01
    • 2019-07-06
    • 1970-01-01
    相关资源
    最近更新 更多