【问题标题】:validating sub-params dependent on parent params with Joi and Hapi使用 Joi 和 Hapi 验证依赖于父参数的子参数
【发布时间】:2017-10-05 20:06:32
【问题描述】:

如何为查询参数的以下逻辑实现验证:

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

但不是同时imagepublication

更新:我尝试了以下代码,但没有成功

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')

【问题讨论】:

    标签: hapijs joi


    【解决方案1】:

    您已接近使用.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')
    }
    

    【讨论】:

      猜你喜欢
      • 2015-10-17
      • 2018-09-24
      • 2018-05-25
      • 1970-01-01
      • 2013-10-19
      • 1970-01-01
      • 1970-01-01
      • 2016-05-16
      • 2019-10-10
      相关资源
      最近更新 更多