如何使用 Joi 验证其键应与外部对象匹配的另一个键其值为数组的嵌套对象?
How to validate nested object whose keys should match with outer objects another key whose value is array using Joi?
我有要验证的对象。
// 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 验证此对象?
您可以验证数组(如果需要),然后创建动态模式并验证它。
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()
})
这应该可以做到。
您必须在 validate()
选项中设置 allowUnknown: true
。
使用object.pattern
and array.length
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
}))
});
我有要验证的对象。
// 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 验证此对象?
您可以验证数组(如果需要),然后创建动态模式并验证它。
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()
})
这应该可以做到。
您必须在 validate()
选项中设置 allowUnknown: true
。
使用object.pattern
and array.length
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
}))
});