创建一个允许任何键但具有定义的对象值的模式
Create a schema which allows any key, but with a defined object value
如果我有这样的数据:
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])
.
Specify validation rules for unknown keys matching a pattern
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()
});
如果我有这样的数据:
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])
.
Specify validation rules for unknown keys matching a pattern
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()
});