How Can I Have Multiple Unique Checks with a Joi Schema Validation?

I have data:

const mockScenario1 = {
  drawingNode: {
    moduleRackOutputs: [
      {
        moduleId: 'module1',
        tilt: 'tilt1',
        rack: {
          framingType: 'framing1'
        }
      },
      {
        moduleId: 'module2',
        tilt: 'tilt1',
        rack: {
          framingType: 'framing1'
        }
      }
    ]
  }
}

I want to ensure that:

  • If there are different moduleId values, I want: Only one module allowed
  • If there are different rack.framingType values, I want: Only one framing type allowed

I have this sort of started with:

Joi.object({
  drawingNode: Joi.object({
    moduleRackOutputs: Joi.array()
      .items(
        Joi.object().keys({
          moduleId: Joi.string().required(),
          tilt: Joi.string().required(),
          rack: Joi.object({
            framingType: Joi.string().required()
          })
        })
      )
      .unique((a, b) => a.moduleId !== b.moduleId)
      .messages({
        'array.unique':
          'The drawing contains more than one module type. Multiple module types are not yet supported by the PVsyst RPA.'
      })
  })
})

Which works for the module, but not the framingType. Seems I can't use multiple unique?

I'd love any help or pointers. Thanks!

1

1 Answer

Here is the Solution. I hope it would help.

Joi.object({
   drawingNode: Joi.object({
     moduleRackOutputs: 
     Joi.array().unique('moduleId').unique('rack.framingType')
     .messages({
        'array.unique':
        'The drawing contains more than one module type. Multiple module types are not yet supported by the PVsyst RPA.'
        })
      })
     })

OR

Joi.object({
  drawingNode: Joi.object({
  moduleRackOutputs: Joi.array()
  .items(
    Joi.object().keys({
      moduleId: Joi.string().required(),
      tilt: Joi.string().required(),
      rack: Joi.object({
        framingType: Joi.string().required()
      })
    })
  )
  .unique((a, b) => a.moduleId === b.moduleId || a.rack.framingType === b.rack.framingType)
  .messages({
    'array.unique':
      'The drawing contains more than one module type. Multiple module types are not yet supported by the PVsyst RPA.'
   })
 })
})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Marcus Vance

Marcus Vance

Cybersecurity & Digital Privacy Researcher

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.

Share this article
Twitter Facebook Pinterest