【问题标题】:Joi Validation - Field is not required when the condition is not metJoi 验证 - 不满足条件时不需要字段
【发布时间】:2021-04-23 00:23:48
【问题描述】:

我正在 nodeJs 中编写更新端点。如果选中某些标志,我想确保不会允许其他字段。

all_restaurant: Joi.boolean().required(),
merchant_id: Joi.when('all_restaurant',{'is':false, 
                then: Joi.string().required(), otherwise:Joi.disallow()})

如果 all_restaurant 为真,我需要在用户尝试包含任何 Mercer_id 时抛出错误,但它仍然允许我更新。 我尝试在字段之后和顶层使用 strict() 但没有任何效果。有什么办法可以做到吗?

【问题讨论】:

    标签: node.js validation joi


    【解决方案1】:

    您可以使用Joi.forbidden 代替 Joi.disallow:

    const schema = Joi.object({
        all_restaurant: Joi.boolean().required(),
        merchant_id: Joi.string().when('all_restaurant', {
            is: false, 
            then: Joi.required(), 
            otherwise: Joi.forbidden()
        })
    })
    

    顾名思义,禁止将密钥标记为禁止。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 2019-05-01
      相关资源
      最近更新 更多