如何基于条件设置数组类型嵌套属性的必填规则
如何根据布尔值条件校验JSON Schema数组项的必填字段
需求明确:当other_ubos为true时,persons数组的每一项都必须填写name、function和email字段;当other_ubos为false时,这些字段无需强制必填。
之前写法的问题
- 尝试的
required: ['persons[number].name']无效,因为JSON Schema的required关键字仅接受当前层级的属性名,不支持数组索引这类路径写法。 - 直接在数组
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块生效:- 强制
persons字段为必填(确保数组存在); - 给
persons数组的每一项添加required规则,指定name、function、email三个字段必须存在并符合各自的格式校验。
- 强制
- 当
other_ubos为false时,then块不生效,persons数组的项无需强制填写这三个字段,完全匹配需求。
内容的提问来源于stack exchange,提问作者Luca Adrian
相关产品推荐
相关产品推荐

