3
votes

I'm using the Joi library to validate an object. I want to make a certain property required when another optional property (at the same level of the same object) is of a certain type, e.g. string. The Joi docs show this example:

const schema = {
    a: Joi.when('b', { is: true, then: Joi.required() }),
    b: Joi.boolean()
};

However, rather than checking that b (for instance) is true, I'd like to check whether it is a string. I've tried this:

const schema = {
    a: Joi.when('b', { is: Joi.string(), then: Joi.required() }),
};

But it doesn't seem to work. If I remove b completely from the object Joi still seems to expect a to be required. If b isn't in the object I don't want any validation placed on a.

I can't find any other examples of people doing this - can anyone help?

1

1 Answers

0
votes

We managed to solve this using object.with. If one key is present (e.g. a), then its peers must be present too (e.g. b).

However, it's not ideal because while we were able to specify that a should be a Joi.string(), object.with is looking for its mere presence rather than its type. So if a non-string a is present a 'should be a string' error will be thrown for a. It should be perfectly fine for a not to be a string - all that should mean is that b is not mandatory. I hope that makes sense.