如何解决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 将密钥标记为禁用。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。