Joi条件验证失效求助:按国家定义JSON Schema属性
问题
想要基于不同国家定义Joi Schema的属性规则,但现有代码验证不通过。
现有Joi Schema代码:
Joi.object({ country: Joi.string().required(), productValue: Joi.when(".country", { is: "VN", then: Joi.number().required(), otherwise: Joi.string() }), pickUpDetails: Joi.object().keys({ ward: Joi.when(Joi.ref('country'), { is: "VN", then: Joi.string().required(), otherwise: Joi.string() }) }), })
待验证的JSON示例:
{ "country": "ID", "productValue": "", "pickUpDetails": { "ward": "" } }
预期country为ID时该JSON能通过验证,但实际未通过。
解决方案
问题出在两个地方,修正后的Schema如下:
Joi.object({ country: Joi.string().required(), productValue: Joi.when(".country", { is: "VN", then: Joi.number().required(), otherwise: Joi.string().allow('') }), pickUpDetails: Joi.object().keys({ ward: Joi.when(Joi.ref('..country'), { is: "VN", then: Joi.string().required(), otherwise: Joi.string().allow('') }) }), })
修正说明
- 空字符串权限:Joi默认的
string()规则不允许空字符串,因此在otherwise分支需要添加.allow(''),明确允许空值通过验证。 - 引用路径修正:在
pickUpDetails嵌套对象中,Joi.ref('country')会查找当前对象下的country属性(不存在),导致条件判断失效。改用Joi.ref('..country')可以正确引用父级对象中的country属性,也可以使用绝对引用Joi.ref('#country')实现相同效果。
内容的提问来源于stack exchange,提问作者Jay Shukla
相关产品推荐
相关产品推荐

