yup/formik最小日期不包括当前日期



我在YUP中具有最低日期约束的emage:

Yup.date()
   .required(strings.RequiredField(strings.Invoice_Label_DueDate))
   .min(new Date(), "Date cannot be in the past")

但是,如果我选择当前日期,它仍然将其计算为过去。请注意,当我做max(new Date(), ...)时,这不会发生。在这种情况下,它包括所有过去的日期,包括当前日期。

编辑:这是问题的示例https://codesandbox.io/s/jznz5vl7lw

您也可以使用:

const today = new Date();
today.setHours(0, 0, 0, 0)

然后

.min(today, 'Date cannot be in the past')

如果要将最低设置为昨天的日期,则可以声明一个变量并将其设置为昨天的日期(也有许多其他方法):

const yesterday = new Date(Date.now() -86400000);

然后:

.min(yesterday, "Date cannot be in the past")

我正在使用它来验证卡到期。它也可以按照正常日期进行操作。

cardExpiry: Yup.string()
      .required("Card Expiry is required")
      .matches(/^(0[1-9]|1[0-2])/d{4}$/, "Invalid Card Expiry (MM/YYYY)")
      .test("cardExpiry", "Date cannot be in the past", function (value) {
        const today = new Date();
        const [expiryMonth, expiryYear] = value.split("/");
        const cardExpiryDate = new Date(
          parseInt(expiryYear),
          parseInt(expiryMonth) - 1
        );
        return cardExpiryDate >= today;
      })

希望这对某人有帮助。

最新更新