如何检查值已在对象验证数组Yup

时间:2020-04-12 11:44:49

标签: formik yup

嗨,我再次与Yup和Formik产生疑问

我需要使用Yup验证Fromik字段数组,我的字段就像

[{startdate:'',endDate:'',name:''},{startdate:'',endDate:'',name:''}]

开始/结束日期是日期对象 在使用Yup和formik之前,我正在进行验证以检查所选日期是否已经退出了

 const checkDate=(selectedDate)=>{
    const isExisting = datas
      .filter((data) => data.startDate !== null || data.endDate !== null)
      .some(
        (data) =>
          new Date(data.startDate).toLocaleDateString() === selectedDate ||
          new Date(data.endDate).toLocaleDateString() === selectedDate,
      );

    if (isExisting) {
      toast.error('Date already exits');
      return false;
    }
}

我知道这有点奇怪。你们中的某些人可能对此有更好的选择。我像这样手动进行所有表单验证,在使用formik和Yup的帮助之后。

要指出的是,如果用户选择了日期,则需要验证日期;如果数组中没有选择的日期,请进行验证。其formik字段数组 我的验证模式就像

export const CheckoutSchema = Yup.object().shape({
  Checkout: Yup.array()
    .of(
      Yup.object().shape({
        name: Yup.string().required(),
        startDate: Yup.date().required(),
        endDate: Yup.date().required(),
      }),
    )
});

我已经检查了一些git页面和堆栈溢出,但是我不知道它是否可以在我的案例here上运行

1 个答案:

答案 0 :(得分:0)

我有一个类似的问题,发现链接的答案很有帮助,但是没有解释它是如何工作的。我能够弄清楚,希望对您有所帮助。

Yup.addMethod(Yup.array, "unique", function(message) {
  return this.test("unique", message, function(list) {
    const mapper = x => x.name;
    const set = [...new Set(list.map(mapper))];
    const isUnique = list.length === set.length;
    if (isUnique) {
      return true;
    }

    const idx = list.findIndex((l, i) => mapper(l) !== set[i]);
    return this.createError({
      path: `[${idx}].name`,
      message: message,
    });
  });
});

const MySchema = Yup.object().shape({
  Checkout: Yup.array()
    .of(
      Yup.object().shape({
        name: Yup.string().required("Required"),
      })
    )
    .unique("Must be unique"),
});

编辑:这实际上将在特定字段上创建错误消息,我发现它更加用户友好。另外,这仅检查name字段的唯一性,并假定formik中的字段名称为${index}.name


由于我没有测试上面的内容,因此这是我的实际代码,其中的对象嵌套在数组中。我已经测试并确认确实可以。

Yup.addMethod(Yup.array, "unique", function(message, path) {
  return this.test("unique", message, function(list) {
    const mapper = x => x.description && x.description.number;
    const set = [...new Set(list.map(mapper))];
    const isUnique = list.length === set.length;
    if (isUnique) {
      return true;
    }

    const idx = list.findIndex((l, i) => mapper(l) !== set[i]);
    return this.createError({
      path: `tests[${idx}].description`,
      message: message,
    });
  });
});

const TestSchema = Yup.object().shape({
  tests: Yup.array()
    .of(
      Yup.object().shape({
        description: Yup.object().required("Required"),
      })
    )
    .unique("Test already added above"),
});