You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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('')
    })
  }),
})

修正说明

  1. 空字符串权限:Joi默认的string()规则不允许空字符串,因此在otherwise分支需要添加.allow(''),明确允许空值通过验证。
  2. 引用路径修正:在pickUpDetails嵌套对象中,Joi.ref('country')会查找当前对象下的country属性(不存在),导致条件判断失效。改用Joi.ref('..country')可以正确引用父级对象中的country属性,也可以使用绝对引用Joi.ref('#country')实现相同效果。

内容的提问来源于stack exchange,提问作者Jay Shukla

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 20:37:35