joi
joi copied to clipboard
Multiple condition
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
orc
can betrue
at the same time - When
b
orc
istrue
,a
isforbidden
otherwisea
isrequired
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}