Joi 验证 - 不满足条件时不需要字段

问题描述

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

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

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

解决方法

您可以使用 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()
    })
})

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