I propose the following syntax:
Example
Requires the presence of another key whenever the value of a key matches the given value.
var schema = {
a: Joi.string(),
b: Joi.any().when('a', Joi.string().regex(/^value$/), Joi.required())
};
If the value of a is "value" then b is required. When can take an array of triplets.
:+1: I really would love this for schema "tables" /cc @nvcexploder
When do you evaluate 'a'? Before or after 'a' itself is evaluated? What if 'a' is '5' and you want it to be a number? should conversion rules apply? This is hard.
My thought was to evaluate 'a' twice. In the schema itself a: Joi.string() and also in the when case. In the case of when you'd create another schema, i.e.
var schema = {
a: Joi.string().regex(/^value$/)
};
If that does not return null, then add Joi.required() to b.
Add it to b means cloning the entire object at validation time. Very expensive.
Partially covered by #260
Woot! Thanks!
Reopening this since the fix didn't address neither #166 nor #188
var Joi = require('joi');
var schema = {
a: Joi.any().when('b', { is: 5, then: Joi.required(), otherwise: Joi.optional() }),
b: Joi.any()
};
var thing = {
b: 5
};
var validate = Joi.validate(thing, schema);
// returns
{
error: null,
value: {
b: 5
}
}
I expected an error saying that a is required because b is 5
@danielb2 Don't do this. Open a new issue next time. In this case, already reported as #334.
Most helpful comment
I propose the following syntax:
Example
Requires the presence of another key whenever the value of a key matches the given value.
If the value of
ais "value" thenbis required.Whencan take an array of triplets.