问题
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')
to get either
server/?type=image&subtype=png
or
server/?type=publication&subtype=book
but not both image
and publication
at the same time?
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')
回答1:
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')
}
来源:https://stackoverflow.com/questions/46582834/validating-sub-params-dependent-on-parent-params-with-joi-and-hapi