Marshall Smith
Marshall Smith

Reputation: 43

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

How to use Yup validation to find the duplicate of contractNum in existingMortgage or newMortgage alone or in both existingMortgage + newMortgage ? Thank you:)

The following is my formik value object and validation schema:

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

Upvotes: 1

Views: 5868

Answers (1)

Muhammad Ali
Muhammad Ali

Reputation: 2648

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,
      });
    });
  });

Above code snippet is to add a unique method in yup.array schema. You can use it like:

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

Upvotes: 1

Related Questions