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

如何通过JSON Schema验证两个不同字段值必须相同?

可以用JSON Schema实现两个字段值必须相同的验证需求

完全可以实现,只要你使用支持JSON Schema Draft 7及以上版本的验证库,借助$data关键字就能引用另一个字段的值,强制两个字段内容一致。

举个常见的密码确认场景示例:

{
  "type": "object",
  "properties": {
    "password": {
      "type": "string",
      "minLength": 8
    },
    "confirmPassword": {
      "type": "string",
      "const": { "$data": "1/password" }
    }
  },
  "required": ["password", "confirmPassword"]
}

关键说明:

  • $data的值1/password是JSON Pointer,指向当前对象下的password字段(1代表向上一级的父对象,因为当前处于confirmPassword的属性定义层级)
  • const关键字要求confirmPassword的值必须和$data引用的password值完全一致,只要两者内容不同,验证就会失败
  • 我们同时标记两个字段为必填,避免空值或缺失字段的情况绕过验证

如果你的验证库不支持$data(比如某些老旧的实现),也可以用一种繁琐的静态匹配方式,但这种方式只能针对固定值,无法动态匹配任意输入:

{
  "type": "object",
  "oneOf": [
    {
      "properties": {
        "password": { "const": "example-password" },
        "confirmPassword": { "const": "example-password" }
      }
    }
  ],
  "required": ["password", "confirmPassword"]
}

显然,优先推荐使用$data的方案,只要你的验证工具支持JSON Schema Draft 7或更高版本,这是最简洁直观的实现方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 10:59:53