question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How throw multiple errors in duplicate check?

See original GitHub issue

This code only throw first duplicate case. I need show all duplicated errors.

yup.addMethod(yup.array, 'unique', function(message, path) {
  return this.test('unique', message, function(list) {
    const duplicates = list
      .map(r => r[path])
      .filter((value, index, self) => self.indexOf(value) !== index);
    if (duplicates.length == 0) return true;

    // find first duplicated.
    list.forEach((row, index) => {
      if (_.includes(duplicates, row[path])) {
        throw this.createError({
          path: `${this.path}[${index}].${path}`,
          message,
        });
      }
    });

    return true;
  });
});
...
const myValidation = yup.object().shape({
  people: yup
    .array()
    .of(
      yup.object().shape(
        _.reduce(
          _.filter(Columns, col => col.validator),
          (result, col) => {
            mixin(result, {
              [col.id]: col.validator,
            });
            return result;
          },
          {},
        ),
      ),
    )
    .unique('email duplicated..', 'email')
});

I used https://github.com/jquense/yup/issues/345 as reference.

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:6 (1 by maintainers)

github_iconTop GitHub Comments

7reactions
AlexLommcommented, Mar 22, 2020

@jquense could you provide an example illustrating how this should be done?

I tried returning an array of errors, but it didn’t work. I believe this happens because the returned array is treated as a “truthy” value, hence the validation is considered passed.

Throwing the array works, however it interrupts other validations despite the { abortEarly: false } option being set.

Is there any way to avoid these problems?

1reaction
AlexLommcommented, Jun 27, 2020

Per my original question:

@jquense could you provide an example illustrating how this should be done?

I tried returning an array of errors, but it didn’t work. I believe this happens because the returned array is treated as a “truthy” value, hence the validation is considered passed.

Throwing the array works, however it interrupts other validations despite the { abortEarly: false } option being set.

Is there any way to avoid these problems?

I ended up implementing a custom validation function that checks if there are any siblings with the same value in its parent array for each object. This allows us to perform checks from the objects’ “perspective”, rather than from the array’s perspective. This is useful because it lets us have multiple errors of the same kind by “tying” them to their respective objects. Example:

import { string, array, object } from "yup";

const people = [
  { name: "John Doe", email: "foo@bar.com" }, // duplicate email
  { name: "Jane Smith", email: "jane@example.com" },
  { name: "Jon Snow", email: "foo@bar.com" } // duplicate email
];

const personSchema = object({ name: string(), email: string() }).test(
  "unique",
  "Emails must be unique.",
  function validateUnique(currentPerson) {
    const otherPeople = this.parent.filter(person => person !== currentPerson);

    const isDuplicate = otherPeople.some(
      otherPerson => otherPerson.email === currentPerson.email
    );

    return isDuplicate
      ? this.createError({ path: `${this.path}.email` })
      : true;
  }
);

const peopleSchema = array().of(personSchema);

try {
  // throws an error because there are two people
  // with the same "foo@bar.com" email in the array
  peopleSchema.validateSync(people, { abortEarly: false });
} catch (error) {
  console.log(JSON.stringify(error, null, 2));
}

Check the CodeSandbox snippet

Read more comments on GitHub >

github_iconTop Results From Across the Web

Check duplicate values between multiple inputs and show ...
This gives us what we need (one flat array) to check all the csTags arrays for duplicates. $scope.verifyDuplicate = function() { var preSort ......
Read more >
how to show two error message for multiple duplicates record ...
To find duplicate you need to loop through the two lists at the same time: first list with your new records (from Trigger.new)...
Read more >
Catching Multiple Exception Types and Rethrowing ...
A catch block that handles multiple exception types creates no duplication in the bytecode generated by the compiler; the bytecode has no replication...
Read more >
Preventing Duplicate Records Based on Multiple Fields in ...
Salesforce Duplicate Management can be achieved using a Set that can store the values of a specific field from all existing records &...
Read more >
Java Catch Multiple Exceptions, Rethrow Exception
If you are catching multiple exceptions and they have similar code, then using this feature will reduce code duplication.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found