是的 - 如何验证对象数组中的重复值?

Yup - How to validate duplicate value in array of objects?

如何使用 Yup 验证在 existingMortgage 或 newMortgage 中单独或在 existingMortgage + newMortgage 中查找 contractNum 的副本?谢谢:)

以下是我的 formik 值对象和验证模式:

{
    "existingMortgage": [
        {
            "contractNum": "123",
            "mortgageAmount": "1000"
        },
        {
            "contractNum": "123",
            "mortgageAmount": "1001"
        },
        {
            "contractNum": "456",
            "mortgageAmount": "1002"
        }
    ],
    "newMortgage": [
        {
            "contractNum": "456",
            "mortgageAmount": "1003"
        },
        {
            "contractNum": "789",
            "mortgageAmount": "1004"
        }
    ]
}

yup.addMethod(yup.array, 'unique', function (field, message) {
    return this.test('unique', message, function (array) {
      const uniqueData = Array.from(
        new Set(array.map((row) => row[field]?.toLowerCase())),
      );
      const isUnique = array.length === uniqueData.length;
      if (isUnique) {
        return true;
      }
      const index = array.findIndex(
        (row, i) => row[field]?.toLowerCase() !== uniqueData[i],
      );
      if (array[index][field] === '') {
        return true;
      }
      return this.createError({
        path: `${this.path}.${index}.${field}`,
        message,
      });
    });
  });

上面的代码片段是在 yup.array 模式中添加一个独特的方法。您可以像这样使用它:

const validationSchema = yup.object({
  existingMortgage: yup.array().unique('contractNum', 'Please provide a unique number.'),
  newMortgage: yup.array().unique('contractNum', 'Please provide a unique number.')
});