通过相互检查值来反应 Formik 验证

问题描述 投票:0回答:1

我正在使用 Formik 进行数据验证,我遇到了一些应该很简单的事情,但我无法弄清楚,即使在阅读文档并查看了几个小时之后也是如此。

基本上我有一个表格,您可以在其中提交带有开始日期和结束日期的多个条目。我使用 yup 来验证日期的格式是否正确,但是当我提交时,我需要表单来检查日期是否不重叠。

下面是仅包含 2 个条目的 formik 值的示例 - 可能还有更多:

(为了简单起见,我只是输入了正常日期,实际上它们以毫秒为单位)

[
    {entryId: 1, startDate: Jan 1 2023 , endDate: Jan 5 2023},
    {entryId:2, startDate Jan 3 2023, endDate: Jan 7 2023}
]

在这种情况下,条目在 1 月 3 日和 1 月 5 日之间有重叠,因此表单在提交时应显示错误。

我已经研究了 formik 文档

docs
中的 validate 函数,但没有运气。

reactjs formik
1个回答
0
投票

我的同事发现了这一点。正如我在问题中提到的,我使用

yup
进行验证,这就是解决此问题所需的方法,而不是直接使用 formik 验证。

我在SO中找到了this帖子,其中暗示了回复。

因此需要创建一个

yup
验证模式,使用
when
test
方法结合并传递到formik
s 
validationSchema`:

const myValidation = yup.object().shape({
  entries: yup.array().of(
    yup.object().shape({
      entryId: yup.number().required("Id is required"),
      startDate: yup.number().required("Date is required").nullable(),
      endDate: yup.number().when("startDate", (startDate, schema) =>
        schema.test({
          test: function (endDate: number) {
            console.log("THIS", this);
            /*
             inside of 'this' object, all the values inside the form can be
             accessed and custom validation can be build comparing these
             values against each other
            */
           validation code here...
          },
        })
      ),
    })
  ),
});
© www.soinside.com 2019 - 2024. All rights reserved.