首页 > 解决方案 > 是的日期验证+ 1天

问题描述

我有一个使用 formik / yup 的表格,我正在对照表格中的其他日期验证日期。我有一个字段expirationDate,我希望至少在输入表单的第二天之后出现。 enteredDate

我目前有这个,它可以工作,但可以验证enteredDate- 问题是如果您将 06/21/21 设置为输入的日期,它接受 06/21/21 作为到期日期 - 我需要将其设置为 06/ 22/21 作为最短日期,或enteredDate + 1 day.

yup.date('Expiration Date')
    .nullable()
    .min(yup.ref('enteredDate'),
        ({ min }) => `Expiration Date needs to be after Entered Date`
    )

我尝试了很多变体

yup.date('Expiration Date')
    .nullable()
    .min(yup.ref('enteredDate') ? daysjs(yup.ref('enteredDate').add(1, 'day') : null,
        ({ min }) => `Expiration Date needs to be after Entered Date`
    )

yup.ref似乎没有返回日期对象,因为错误是TypeError: The value of field could not be cast to a value that satisfies the schema type: "date".

我怎样才能告诉 yup 第二天使用?

标签: javascriptvalidationformikyup

解决方案


您需要使用.when方法将一个字段连接到另一个字段。文档。

这应该按预期工作:

const schema = object({
  enteredDate: date().required(),
  expirationDate: date().when("enteredDate", (enteredDate, schema) => {
    if (enteredDate) {
      // This can be calculated in many ways. Just be sure that its type is `Date` object
      const dayAfter = new Date(enteredDate.getTime() + 86400000);

      return schema.min(dayAfter);
    }

    return schema;
  })
});

推荐阅读