joi icon indicating copy to clipboard operation
joi copied to clipboard

Nested objects validation not working as expected

Open MallRoy opened this issue 2 years ago • 1 comments

Support plan

  • *is this issue currently blocking your project?: yes
  • *is this issue affecting a production system?: yes

Context

  • node version: 14.17.0
  • module version: 17.9.1
  • environment : node
  • *used with: express framework
  • any other relevant information: Please test the below schema in https://joi.dev/tester/

How can we help?

I am expecting error in this case, but the validation is getting success.

Joi.object({
  isTemplate: Joi.boolean().optional().valid(true, false),
  fileId: Joi.string().optional(),
  req:Joi.object({ 
    template: Joi.alternatives().conditional('isTemplate', {
      is: Joi.valid(true),
      then: Joi.string().required(),
      otherwise: Joi.string().optional(),
    })
  })
});

Sample data: { 
 isTemplate: true,
 fileId: "435"
}

MallRoy avatar Jun 27 '23 13:06 MallRoy

You need to add .required() to the req: Joi.object(/* ... */) part:

Joi.object({
  isTemplate: Joi.boolean().optional().valid(true, false),
  fileId: Joi.string().optional(),
  req:Joi.object({ 
    template: Joi.alternatives().conditional('isTemplate', {
      is: Joi.valid(true),
      then: Joi.string().required(),
      otherwise: Joi.string().optional(),
    })
  }).required()
});

BenceSzalai avatar Aug 07 '23 15:08 BenceSzalai

@MallRoy change .alternatives().conditional to .when and viola

aiyeola avatar May 07 '24 06:05 aiyeola