validating sub-params dependent on parent params with Joi and Hapi

放肆的年华 提交于 2019-12-24 09:36:24

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!