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

Joi Validation - Field is not required when the condition is not met

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

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

如果 all_restaurant 为真,我需要在用户尝试包含任何 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 将密钥标记为禁止。