日期范围验证 - 开始日期不能与 jquense / yup 中的结束日期相同

IT技术 reactjs validation yup
2021-05-12 07:46:31

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