I'm using node module Joi to make some validations and I am having trouble using the .or() method.
In their documentation they specify the use as:
var schema = Joi.object().keys({
a: Joi.any(),
b: Joi.any()
}).or('a', 'b');
But I'm trying to validate an Object and I wanted to use .or() for checking for properties nested under different properties, got it? Something like:
var schema = Joi.object().keys({
body:{
device:{
smthelse: Joi.any(),
ua: Joi.string()
}
},
headers:{
'user-agent': Joi.string()
}).or('body.device.ua', 'headers.user-agent');
But I can't seem to make it work. Does anyone know if I'm missing something? Is that way to user .or() for nested objects?
Thanks!
I'm using node module Joi to make some validations and I am having trouble using the .or() method.
In their documentation they specify the use as:
var schema = Joi.object().keys({
a: Joi.any(),
b: Joi.any()
}).or('a', 'b');
But I'm trying to validate an Object and I wanted to use .or() for checking for properties nested under different properties, got it? Something like:
var schema = Joi.object().keys({
body:{
device:{
smthelse: Joi.any(),
ua: Joi.string()
}
},
headers:{
'user-agent': Joi.string()
}).or('body.device.ua', 'headers.user-agent');
But I can't seem to make it work. Does anyone know if I'm missing something? Is that way to user .or() for nested objects?
Thanks!
Share Improve this question asked May 13, 2015 at 23:50 Thiago LoddiThiago Loddi 2,3405 gold badges23 silver badges36 bronze badges2 Answers
Reset to default 5Thanks for the answer Bulkan, but that actually didn't work. I posted the same question in hapijs github's issues section and got a solution, here is it (posted by DavidTPate):
The way you are doing it doesn't appear possible to me since it doesn't look like object.or() at that top level supports referencing nested items. You could do it with alternatives though.
You should be able to do
var bodySchema = Joi.object().keys({
body: Joi.object().keys({
device: Joi.object().keys({
ua: Joi.string().required()
}).required();
}).required();
}).required();
var headerSchema = Joi.object().keys({
headers: Joi.object().keys({
'user-agent': Joi.string().required()
}).required()
}).required();
var schema = Joi.alternatives().try(bodySchema, headerSchema);
Here is the link for more info: https://github./hapijs/joi/issues/643
The nested Objects need to be Joi schemas as well like so;
var schema = Joi.object().keys({
body: Joi.object().keys({
device: Joi.object().keys({
smthelse: Joi.any(),
ua: Joi.string()
}
}),
headers: Joi.object().keys({
'user-agent': Joi.string()
})
}).or('body.device.ua', 'headers.user-agent');