我有要验证的对象。
// valid object because all values of keys are present in details object
var object = {
details: {
key1: 'stringValue1',
key2: 'stringValue2',
key3: 'stringValue3'
},
keys: ['key1', 'key2', 'key3']
}
// invalid object as key5 is not present in details
var object = {
details: {
key4: 'stringValue4'
},
keys: ['key4', 'key5']
}
// invalid object as key5 is not present and key8 should not exist in details
var object = {
details: {
key4: 'stringValue4',
key8: 'stringValue8',
},
keys: ['key4', 'key5']
}
keys
中存在的所有键也应出现在details
中。
我尝试使用Joi.ref()
var schema = Joi.object({
details: Joi.object().keys(Object.assign({}, ...Object.entries({...Joi.ref('keys')}).map(([a,b]) => ({ [b]: Joi.string() })))),
keys: Joi.array()
})
但是这不起作用,因为Joi.ref('keys')
将在验证时得到解决。
如何使用Joi验证此对象?
答案 0 :(得分:1)
var schema = Joi.object({
details: Joi.object().pattern(Joi.in('keys'), Joi.string()),
keys: Joi.array().length(Joi.ref('details', {
adjust: (value) => Object.keys(value).length
}))
});
答案 1 :(得分:0)
您可以验证数组(如果需要),然后创建一个动态架构并对其进行验证。
const arrSchema = Joi.object({
keys: Joi.array()
});
然后
const newSchema = Joi.object({
details: Joi.object().keys(data.keys.reduce((p, k) => {
p[k] = Joi.string().required();
return p;
},{})),
keys: Joi.array()
})
这应该可以做到。
您必须在allowUnknown: true
选项中设置validate()
。