简体   繁体   English

使用JSON模式对另一个属性进行验证

[英]Validate property against another with JSON Schema

In the model below, "category_id" property should be required only if "detail" array is empty. 在下面的模型中,仅当“详细信息”数组为空时,才需要“ category_id”属性。

If "detail" array is not empty, "category_id" property is not required. 如果“详细信息”数组不为空,则不需要“ category_id”属性。

How can I do this with JSON Schema? 如何使用JSON模式执行此操作?

{
    "description": "Expense model validation.",
    "type": "object",
    "properties": {
        "description": {
            "type": "string"
        },
        "category_id": {
            "type": "string"
        },
        "detail": {
            "type": "array",
            "items": {
                "description": "Expense detail",
                "type": "object",
                "properties": {
                    "description": {
                        "type": "string"
                    }
                },
                "required": [ "description" ]
            }
        }
    },
    "required": [ "description", "category_id" ]
}

You can use anyOf to check that either category_id is present, or detail is present and has at least one item. 您可以使用anyOf来检查是否存在category_iddetail是否存在并且至少有一项。

{
  "description": "Expense model validation.",
  "type": "object",
  "properties": {
    "description": { "type": "string" },
    "category_id": { "type": "string" },
    "detail": {
      "type": "array",
      "items": {
        "description": "Expense detail",
        "type": "object",
        "properties": {
          "description": { "type": "string" }
        },
        "required": ["description"]
      }
    }
  },
  "required": ["description"],
  "anyOf": [
    { "required": ["category_id"] },
    {
      "properties": {
        "detail": { "minItems": 1 }
      },
      "required": ["detail"]
    }
  ]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM