I'm trying to use when() to set conditions for fields that are defined inside an array item. I haven't had any luck. Am I missing something? I can't think of a reason this shouldn't be supported.
Thought this might be related to #892 but even with code post #893 I'm not seeing what I expect.
var Joi = require('joi');
var schema = Joi.object().keys({
a: Joi.number(),
b: Joi.array().items({
c: Joi.when('a', {
is: 1,
then: Joi.string().valid(['x'])
})
})
});
var data = {
a: 1,
b: [{c: 'not-x'}]
};
Joi.validate(data, schema);
//=> { error: null, value: { a: 1, b: [ [Object] ] } }
@hueniverse are you saying this should be fixed by #893 then?
When it's published yes.
Can you verify? I may be crazy but as I mentioned above, I tried running the example above against the current master code from git. I still get no validation error.
Sorry no. You can't do what you want. You are trying to reference a key outside the object you are in. The c property inside the array object has no siblings which the reference is trying to resolve. You are trying to climb out of that object and into the parent of the array which is not supported (and is unlikely to be ever supported because it will create really broken rules).
@jparkerCAA I got same, I fixed my issue via context. I'm not sure if this one may help you. Maybe there is another way around to access parent ref
var Joi = require('joi');
var schema = Joi.object().keys({
a: Joi.number(),
b: Joi.array().items({
c: Joi.when('$a', {
is: 1,
then: Joi.string().valid(['x'])
})
})
});
var data = {
a: 1,
b: [{c: 'not-x'}]
};
Joi.validate(data, schema, {
context: {
a: data.a
}
});
There is not, parent refs are inaccessible by design. Here they are considered siblings, which is why it works.
Most helpful comment
@jparkerCAA I got same, I fixed my issue via context. I'm not sure if this one may help you. Maybe there is another way around to access parent ref