0
votes

I'm using Joi to validate the headers on a HTTP request. I have two headers. If FOO is present then BAR is required, otherwise BAR is optional. This works:

'FOO': Joi.string().optional(),
'BAR': Joi.string().when('FOO', { is: Joi.not(''), then: Joi.required() })

If I want FOO to be a numeric value then this works:

'FOO': Joi.number().integer().default(0).optional(),
'BAR': Joi.string().when('FOO', { is: Joi.number().min(1), then: Joi.required() })

However if I omit the default(0) then Joi thinks that BAR is required when FOO is not present. Is that correct behavior? Is there a better way to handle this?

1

1 Answers

0
votes

This can be made a lot simpler by using .with(). Consider the following schema:

const schema = Joi.object().keys({
    FOO: Joi.number().default(0).min(1),
    BAR: Joi.string()
}).with('FOO', 'BAR');

The .with() forces BAR to be required only when FOO is present.

Also similar to your example it will also ensure FOO must be greater than or equal to 1 if it's actually in the payload, else Joi will default it to 0.