如何有条件地设置数组类型的嵌套属性



我有这个schema是由jsonforms使用。

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'],
},
};

我想设置一个条件,如果other_ubostrue,每个数组项都应该有name``functionemail所需。

基本上就是这样的

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[number].name'],
},
};

直接在

上设置
{
type: 'object',
properties: {
name: {
type: 'string',
pattern: "^[-'a-zA-ZÀ-ÖØ-öø-ÿ ]+$",
},
function: {
type: 'string',
pattern: "^[-'a-zA-ZÀ-ÖØ-öø-ÿ ]+$",
},
email: {
type: 'string',
pattern: '^(.+)@(.+)$',
},
},
}

不会有预期的效果,因为即使other_ubosfalse

它也会验证

我最终做的是有条件地设置整个属性对象:

const schema = {
$schema: 'http://json-schema.org/draft-07/schema#',
type: 'object',
properties: {
other_ubos: {
type: 'boolean',
},
},
if: {
properties: {
other_ubos: {
const: true,
},
},
},
then: {
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: ['name', 'function', 'email'],
},
},
},
},
required: ['other_ubos'],
};

或者更好的解决方案:您可以在JSON Schema中部分地重复自己。这并不重要,因为结束验证只是指定的所有内容的并集。

JSON 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"
]
}
}
}
}
}

最新更新