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

如何基于条件设置数组类型嵌套属性的必填规则

如何根据布尔值条件校验JSON Schema数组项的必填字段

需求明确:当other_ubos为true时,persons数组的每一项都必须填写name、function和email字段;当other_ubos为false时,这些字段无需强制必填。

之前写法的问题

  1. 尝试的required: ['persons[number].name']无效,因为JSON Schema的required关键字仅接受当前层级的属性名,不支持数组索引这类路径写法。
  2. 直接在数组items的对象结构中添加required,会导致无论other_ubos取值如何,这三个字段都会被校验为必填,不符合条件触发的需求。

正确的Schema写法

要实现条件性的数组项校验,需要在then块中对persons的items进行针对性约束,具体代码如下:

const schema = {
  $schema: 'http://json-schema.org/draft-07/schema#',
  type: 'object',
  properties: {
    other_ubos: {
      type: 'boolean',
    },
    persons: {
      type: 'array',
      items: {
        type: 'object',
        properties: {
          name: {
            type: 'string',
            pattern: "^[-'a-zA-ZÀ-ÖØ-öø-ÿ ]+$",
          },
          function: {
            type: 'string',
            pattern: "^[-'a-zA-ZÀ-ÖØ-öø-ÿ ]+$",
          },
          email: {
            type: 'string',
            pattern: '^(.+)@(.+)$',
          },
        },
      },
    },
  },
  required: ['other_ubos'],
  if: {
    properties: {
      other_ubos: {
        const: true,
      },
    },
  },
  then: {
    required: ['persons'],
    properties: {
      persons: {
        items: {
          required: ['name', 'function', 'email']
        }
      }
    }
  },
};

关键说明

  • 当other_ubos为true时,then块生效:
    1. 强制persons字段为必填(确保数组存在);
    2. 给persons数组的每一项添加required规则,指定name、function、email三个字段必须存在并符合各自的格式校验。
  • 当other_ubos为false时,then块不生效,persons数组的项无需强制填写这三个字段,完全匹配需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 09:31:33