使用Joi和Hapi验证依赖于父参数的子参数 [英] validating sub-params dependent on parent params with Joi and Hapi
本文介绍了使用Joi和Hapi验证依赖于父参数的子参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何为以下查询参数逻辑实现验证:
How can I implement validation for something like the following logic for query params:
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
吗?
更新:我尝试了以下代码,但没有成功
Update: I tried the following code but no luck
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
结构的函数之后,就可以将它们链接在一起.不幸的是,文档并未对此做清楚的说明.
You're close with the use of .when()
. Rather than trying to put all of the permutations in a single .when()
call, you can chain them together as the function descends from the common any
structure. Unfortunately the documentation doesn't make this particularly clear.
{
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')
}
这篇关于使用Joi和Hapi验证依赖于父参数的子参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文