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

cashValue枚举为Y时JSON Schema必填字段校验及Angular适配问询

解决JSON Schema条件必填校验问题

原定义中的问题

先梳理原Schema和Payload存在的明显错误:

  • Schema里cashValue被定义为数组类型,但Payload传入的是字符串"Y",类型不匹配;且cashValueDetails错误嵌套在cashValue属性内,实际应和cashValue同级。
  • Schema的required数组中inCome4未加引号,属于语法错误;同时Schema里未定义inCome4这个属性。
  • Payload中inCome1等字段的结构是{"type": 数值},但Schema定义为number类型,结构不匹配,应直接传递数值。

正确的JSON Schema实现

使用JSON Schema的if/then关键字实现条件校验(需支持draft-07及以上版本):

{
  "type": "object",
  "properties": {
    "cashValue": {
      "type": "string",
      "enum": ["Y", "N"]
    },
    "cashValueDetails": {
      "type": "object",
      "properties": {
        "inCome1": { "type": "number" },
        "inCome2": { "type": "number" },
        "inCome3": { "type": "number" },
        "inCome4": { "type": "number" },
        "inCome8": { "type": "number" }
      }
    }
  },
  "if": {
    "properties": {
      "cashValue": { "const": "Y" }
    },
    "required": ["cashValue"]
  },
  "then": {
    "required": ["cashValueDetails"],
    "properties": {
      "cashValueDetails": {
        "required": ["inCome1", "inCome2", "inCome3", "inCome4"]
      }
    }
  }
}

校验逻辑说明

  • 当cashValue取值为"Y"时:
    1. 必须存在cashValueDetails字段
    2. cashValueDetails内必须包含inCome1、inCome2、inCome3、inCome4四个必填字段,且每个字段必须是数值类型
  • 当cashValue取值为"N"时:
    • cashValueDetails可选,其中的字段也都非必填

修正后的Angular Payload示例

{
  "cashValue": "Y",
  "cashValueDetails": {
    "inCome1": 200,
    "inCome2": 100,
    "inCome3": 400,
    "inCome4": 500,
    "inCome8": 350
  }
}

适配Angular的注意事项

  • 确保Angular项目中使用的JSON校验库支持JSON Schema draft-07及以上版本(比如ajv,可通过npm install ajv引入)
  • 在Angular表单校验中,将上述Schema传入校验库,对接口接收的Payload进行校验
  • 如果cashValue确实需要是数组类型(比如多选场景),可调整Schema中cashValue的定义为数组,并修改if条件为contains: { const: "Y" },表示数组中包含"Y"时触发必填校验

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 08:47:43