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

如何使用JSON Schema Validator实现特定条件下的长度校验?

答案

完全可以实现,你使用的JSON Schema 2019-09版本原生支持if/then条件校验关键字,针对你的需求可以直接在根Schema下新增allOf字段包裹两组独立的条件校验规则即可,不需要改动原有Schema的其他结构。

完整修改后的Schema代码

{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "description": "My sample Json",
  "type": "object",
  "properties": {
    "eventId": {
      "description": "The event Indetifier",
      "type": [ "number", "string" ]
    },
    "serviceType": {
      "description": "The service type. It can be either ABC or EFG",
      "enum": [ "ABC", "EFG" ]
    },
    "parameters": { "$ref": "/schemas/parameters" }
  },
  "required": [ "eventId", "serviceType" ],
  "allOf": [
    {
      "if": {
        "properties": {
          "eventId": { "const": "100" },
          "serviceType": { "const": "ABC" }
        },
        "required": ["eventId", "serviceType"]
      },
      "then": {
        "properties": {
          "parameters": {
            "properties": {
              "activityType": {
                "type": "string",
                "minLength": 10
              }
            },
            "required": ["activityType"]
          }
        },
        "required": ["parameters"]
      }
    },
    {
      "if": {
        "properties": {
          "eventId": { "const": "200" },
          "serviceType": { "const": "EFG" }
        },
        "required": ["eventId", "serviceType"]
      },
      "then": {
        "properties": {
          "parameters": {
            "properties": {
              "activitySubType": {
                "type": "string",
                "minLength": 20
              }
            },
            "required": ["activitySubType"]
          }
        },
        "required": ["parameters"]
      }
    }
  ],
  "$defs": {
    "parameters": {
      "$id": "/schemas/parameters",
      "$schema": "http://json-schema.org/draft-07/schema#",
      "description": "Other Parameters",
      "type": "object",
      "properties": {
        "activityType": {
          "description": "The activity type",
          "type": [ "null", "string" ]
        },
        "activitySubType": {
          "description": "The activity sub type",
          "type": [ "null", "string" ]
        }
      }
    }
  }
}

规则说明

  • 两组条件规则相互独立,只要满足对应if块的判断条件,就会触发对应then块的校验规则,不满足则不会触发,不影响其他场景的校验
  • 如果你需要同时兼容eventId为数字类型的匹配(比如数字100也触发第一条规则),可以将eventId的const规则替换为"enum": [100, "100"]即可
  • then块中重新指定了对应字段的type为string,覆盖了原定义中允许null的配置,同时新增了最小长度限制,且新增了对应字段的必填校验,完全符合需求

内容的提问来源于stack exchange,提问作者Ritu Jain

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 07:54:03