Joi Validations: If object matches the schema validate against it from multiple items

There are some typos in your files and validators.

First of Joi.array is a function and needs to be called as one.

// This is incorrect
data2: Joi.array
...
additional: Joi.array

// Should be changed to this where array is invoked as a function
data2: Joi.array()
...
additional: Joi.array()

Additionally, I’ve added a fourth validator which basically passes all sample objects which have a type greater than 3.

.when(
  Joi.object({
    type: Joi.number().greater(3),
  }).unknown(),
  {
    then: Joi.object().unknown(true),
  }
)

And there are other typos in your validators e.g missing brackets – I created a fixed version of your validator in codesandbox.

Validation is still failing in the codesandbox since in profile2.js postal is declared as string, but in your samples array it is a number for the second object, search for postal: 123 and change it to postal: “123” or modify the validation of postal from postal: Joi.string() to postal: Joi.number()

This way if one of the validators passes then the other ones won’t throw an error, and if the type is greater than 3 it will pass validation.

Leave a Comment

tech