问题描述
如果我有这样的数据:
params: {
fieldOne: {
a: 'a1',b: 'b1'
},fieldTwo: {
a: 'a2',b: 'b2'
}
}
我正在尝试编写一个joi模式,该模式将验证params
是具有任何键的对象,这些键的值分别是带有a
和b
的对象。
我正在努力弄清楚如何在params
的值中允许任何键,但仍要验证该值。
const schema = joi.object().keys({
params: joi.object().required().keys({
// How to allow any keys here,but require that the value is an object with keys a and b?
})
});
解决方法
您可以使用object.pattern(pattern,schema,[options])
。
为匹配模式的未知密钥指定验证规则
const schema = joi.object().keys({
params: joi.object().pattern(
// this is the 'pattern' of the key name
// you can also use a regular expression for further refinement
joi.string(),// this is the schema for the key's value
joi.object().keys({
a: joi.string().required(),b: joi.string().required()
})
).required()
});