hapijs / joi

The most powerful data validation library for JS
Other
20.95k stars 1.51k forks source link

List of errors for all duplications #1814

Closed sohai closed 5 years ago

sohai commented 5 years ago

Context

What are you trying to achieve or the steps to reproduce?

I would like to get errors for all rows that are not unique.

const data = [
         {
          carrierCode: 'A1',
          carrierName: 'Brand New',
        },
        {
          carrierCode: 'AA',
          carrierName: 'American Airlines',
        },
        {
          carrierCode: 'AA',
          carrierName: 'American Airlines',
        },
        {
          carrierCode: 'AB',
          carrierName: 'Air Berlin',
        },
        {
          carrierCode: 'AC',
          carrierName: 'Air Canada Group',
        },
        {
          carrierCode: 'AF',
          carrierName: 'Air France',
        },
        {
          carrierCode: 'AH',
          carrierName: 'Air Algerie',
        },
        {
          carrierCode: 'AF',
          carrierName: 'Air-France',
        },
      ]

const schema = Joi.array()
      .items(
        Joi.object({
          carrierCode: Joi.string().required(),
          carrierName: Joi.string().required(),
        }),
      )
      .unique((left, right) => left.carrierCode === right.carrierCode)
      .required()

const result = Joi.attempt(data, schama);

Which result you had ?

[1] "value" position 2 contains a duplicate value

What did you expect ?

A list of errors for all duplicated values.

Eventually, I would like to get to the point where I could have an error related to a unique field. I guess that requires

 Joi.array()
      .items(
        Joi.object({
          carrierCode: CustomJoi.string().required().uniqueIn(/*How to get access to parent array in custom extension?*/),
          carrierName: Joi.string().required(),
        }),
      )
hueniverse commented 5 years ago

This is not possible due to the way the entire rule system is set up. Because unique() is a rule, it can only return a single error. You will need to do post processing yourself to find the full list of duplication.