如何检查值是否已存在于对象验证数组中是的

Dev*_*Dev 1 yup formik

嗨,我又来了,是的,我有疑问

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

[{startdate:'',endDate:'',name:''},{startdate:'',endDate:'',name:''}]
Run Code Online (Sandbox Code Playgroud)

开始/结束日期是日期对象在使用 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我知道这有点奇怪。你们中的一些人可能对此有更好的选择。我像这样手动进行所有表单验证,在使用 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(),
      }),
    )
});
Run Code Online (Sandbox Code Playgroud)

我已经检查了一些 git 页面和堆栈溢出,但我不知道它是否适用于我的情况

Sha*_*rud 5

我遇到了类似的问题,发现链接的答案很有帮助,但没有解释它是如何工作的。我能够弄清楚所以希望这会更有帮助。

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"),
});
Run Code Online (Sandbox Code Playgroud)

编辑:这实际上会在特定字段创建错误消息,我发现这对用户更友好。另外,这只是检查名称字段的唯一性,并假设 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"),
});
Run Code Online (Sandbox Code Playgroud)