Search code examples
joi

JOI validation when condition not working as expected


I have the following JOI schema defined;

schema = Joi.object({
  flag: Joi.boolean()
    .required(),
  toolDetail: Joi.array().items(
    Joi.object({
      amount: Joi.number()
        .min(0)
        .max(499.99)
        .precision(2)
        .options({ convert: false })
        .when('flag', {
          is: true,
          then: Joi.number().required(),
          otherwise: Joi.number()
            .strip()
            .optional()
            .allow(''),
        }),
      tool: Joi.string()
        .min(0)
        .max(500)
        .when('flag', {
          is: true,
          then: Joi.string().required(),
          otherwise: Joi.string()
            .strip()
            .optional()
            .allow(''),
        }),
    }),
  ),
});

I have confirmed that the flag is being set correctly, but it seems that 'amount' and 'tool' is always hitting the otherwise condition, regardless of the value set in the 'flag'.

Is there something incorrect in my definition?


Solution

  • Works as expected once I added 4 dots prefix to the flag

    .when('....flag', { 
    

    https://joi.dev/api/?v=17.2.1#relative-references