【发布时间】:2018-02-16 19:26:35
【问题描述】:
我有一个如下所示的数据集:
有效示例数据
{
type: "step",
label: "Step 1",
fields: [
// An optional field
{
type: "email",
label: "Your Email"
},
// A field that is required and can be either amount|preset
{
type: "amount",
label: "Amount"
},
// A field that is required and can be either credit_card|ach
{
type: "credit_card",
label: "Credit Card"
}
]
}
fields 数组可以包含许多不同类型的对象。上面的例子是有效的。
无效的示例数据
{
type: "step",
label: "Step 1",
fields: [
{
type: "email",
label: "Your Email"
},
{
type: "credit_card",
label: "Credit Card"
}
]
}
这应该会出错,因为它不包含 amount 或 presets 类型的对象
验证规则
为了有效,fields 需要包含 2 个对象。
其中 1 个必须是
{ type: "amount" }或{ type: "presets" }其中 1 个必须是
{ type: "credit_card" }或{ type: "ach" }这两者的任意组合都会使
fields有效。
JSON 架构
这是我的(失败的)JSON 架构:
{
"title": "step",
"type": "object",
"properties": {
"type": {
"title": "type",
"type": "string"
},
"label": {
"title": "label",
"type": "string"
},
"fields": {
"title": "fields",
"description": "Array of fields",
"type": "array",
"additionalItems": true,
"minItems": 1,
"items": {
"type": "object",
"anyOf": [
{ "properties": { "type": { "enum": ["amount", "preset"] } } },
{ "properties": { "type": { "enum": ["credit_card", "ach"] } } }
],
"properties": {
"type": {
"type": "string",
}
}
},
}
},
"required": ["type", "label", "fields"]
}
Here is the JSON Schema Validation Reference
我认为在contains、anyOf、allOf、oneOf 和enum 之间我应该能够做到这一点?
【问题讨论】:
标签: javascript json validation jsonschema