joi icon indicating copy to clipboard operation
joi copied to clipboard

Multiple condition

Open sm2017 opened this issue 2 years ago • 1 comments

Support plan

  • is this issue currently blocking your project? (yes/no): no
  • is this issue affecting a production system? (yes/no): no

Context

  • node version: v14.17.6
  • module version: 17.4.2
  • environment (e.g. node, browser, native): node
  • used with (e.g. hapi application, another framework, standalone, ...): standalone
  • any other relevant information:

How can we help?

const schema = {
    a: Joi.any(),
    b: Joi
      .boolean()
      .default(false),
    c: Joi
      .boolean()
      .default(false)
}

How can I fix the abovementioned Joi schema to matches the following rules, I tried nested when but not works

  • One of b or c can be true at the same time
  • When b or c is true, a is forbidden otherwise a is required

sm2017 avatar Sep 28 '21 05:09 sm2017

OMG!! the order of rules definition is important!! why?

Joi.object( {
  a: Joi
      .boolean()
      .default(false),
  b: Joi
      .boolean()
      .default(false),
  c: Joi.string().when(
    'a', {
      is: false,
      then: Joi.when(
        'b', {
          is: false,
          then: Joi.string().required()
        }
      )
    }
  ),
})

Works while

Joi.object( {
  c: Joi.string().when(
    'a', {
      is: false,
      then: Joi.when(
        'b', {
          is: false,
          then: Joi.string().required()
        }
      )
    }
  ),
  a: Joi
      .boolean()
      .default(false),
  b: Joi
      .boolean()
      .default(false),
})

not works, the default value in the second schema is not set when the when is checking, So If you validate an empty object {}, the first schema has Validation Error: "c" is required error while the second Passed with {a: false, b: false}

sm2017 avatar Sep 28 '21 06:09 sm2017