Shubhashish Pradhan
Shubhashish Pradhan

Reputation: 21

Joi Validation || In an array of object, at least one object should contain a particular value of a key

I need a schema for below array of object:

option = [
    {
        answer: '',
        isTrue: false
    },
    {
        answer: '',
        isTrue: true
    },
]

So far I wrote below schema:

Joi.array().items(Joi.object({
   answer: Joi.string().required(),
   isTrue: Joi.boolean().required()
}).unknown()).min(2).required()

Problem: I need to verify atleast one object should have "isTrue" key's value to be "true" (boolean)

Upvotes: 2

Views: 3269

Answers (1)

Poçi
Poçi

Reputation: 253

 let optionsValidation = Joi.object().keys({
      answer: Joi.string().required(),
      isTrue: Joi.boolean().required()
    });
    
    //replace with your field name
    options: Joi.array()
          .items(optionsValidation)
          .has(
            Joi.object().keys({
              answer: Joi.string().required(),
              isTrue: Joi.boolean().invalid(false).required();
            }),
          )

Maybe you need to change smth to adapt it on your code but this should work. It makes sure that at least one object on array should have an answer and it should be true.

Upvotes: 4

Related Questions