【问题标题】:How to use JSON Schema to require one of two fields如何使用 JSON Schema 来要求两个字段之一
【发布时间】:2017-05-10 08:03:05
【问题描述】:

我想验证 JSON 以使两个字段之一成为强制性字段。

假设我们有两个字段(电子邮件地址和电话号码)。我想确保记录有效需要两个字段之一。

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "id": "ExampleID-0212",
  "title": "objectExamples",
  "description": "Demo",
  "type": "object",
  "properties": {
    "RecordObject": {
      "type": "object",
      "properties": {
        "emailAddress": {
          "type": "string"
        },
        "PhoneNumber": {
          "type": "number"
        }
      }
    }
  },
  "required": [
    "RecordObject"
  ]
}

【问题讨论】:

    标签: json jsonschema json-schema-validator


    【解决方案1】:

    你需要添加:

    "anyOf": [
      { "required":
        [ "emailAddress" ] },
      { "required":
        [ "PhoneNumber" ] }
    ]
    

    到 RecordObject 属性的架构。

    它要求至少存在一个字段。如果您只需要一个字段(即,不是两个),您需要使用“oneOf”关键字(其余的应该相同)。

    This reference of JSON Schema keywords 很有用。

    【讨论】:

    【解决方案2】:

    来自 ESP 的 Sooperb 答案.. 来自 jsonSchema ...

    您也可以通过条件进行验证..见下文

     if(EmailAddress == null && PhoneNumber == null){
         //statements or error message response
    }
    

    【讨论】:

      猜你喜欢
      • 2017-07-05
      • 2015-05-06
      • 2022-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多