使用 Joi 和 Hapi 验证依赖于父参数的子参数
validating sub-params dependent on parent params with Joi and Hapi
如何为查询参数的以下逻辑实现验证:
if (type is 'image') {
subtype is Joi.string().valid('png', 'jpg')
else if (type is 'publication') {
subtype is Joi.string().valid('newspaper', 'book')
获得其中之一
server/?type=image&subtype=png
或
server/?type=publication&subtype=book
但不能同时 image
和 publication
?
更新: 我尝试了以下代码,但没有成功
type: Joi
.string()
.valid('image', 'publication', 'dataset')
.optional(),
subtype: Joi
.when('type',
{
is: 'image',
then: Joi
.string()
.valid('png', 'jpg')
.optional()
},
{
is: 'publication',
then: Joi
.string()
.valid('newspaper', 'book')
.optional()
}
)
.optional()
.description('subtype based on the file_type')
您即将使用 .when()
。与其尝试将所有排列放在单个 .when()
调用中,不如将它们链接在一起,因为函数从公共 any
结构下降。不幸的是,文档并没有特别清楚地说明这一点。
{
type: Joi.string()
.valid('image', 'publication', 'dataset')
.optional(),
subtype: Joi.string()
.optional()
.when('type', {is: 'image', then: Joi.valid('png', 'jpg')})
.when('type', {is: 'publication', then: Joi.valid('newspaper', 'book')})
.description('subtype based on the file_type')
}
如何为查询参数的以下逻辑实现验证:
if (type is 'image') {
subtype is Joi.string().valid('png', 'jpg')
else if (type is 'publication') {
subtype is Joi.string().valid('newspaper', 'book')
获得其中之一
server/?type=image&subtype=png
或
server/?type=publication&subtype=book
但不能同时 image
和 publication
?
更新: 我尝试了以下代码,但没有成功
type: Joi
.string()
.valid('image', 'publication', 'dataset')
.optional(),
subtype: Joi
.when('type',
{
is: 'image',
then: Joi
.string()
.valid('png', 'jpg')
.optional()
},
{
is: 'publication',
then: Joi
.string()
.valid('newspaper', 'book')
.optional()
}
)
.optional()
.description('subtype based on the file_type')
您即将使用 .when()
。与其尝试将所有排列放在单个 .when()
调用中,不如将它们链接在一起,因为函数从公共 any
结构下降。不幸的是,文档并没有特别清楚地说明这一点。
{
type: Joi.string()
.valid('image', 'publication', 'dataset')
.optional(),
subtype: Joi.string()
.optional()
.when('type', {is: 'image', then: Joi.valid('png', 'jpg')})
.when('type', {is: 'publication', then: Joi.valid('newspaper', 'book')})
.description('subtype based on the file_type')
}