在react-jsonschema-form中包含必填字段的可选对象

时间:2017-08-22 14:43:53

标签: forms reactjs jsonschema json-schema-validator

给定如下所示的json模式,react-jsonschema-form验证器基本上同时需要shipping_addressbilling_address,即使billing_address未按要求列出。这是因为address类型需要它的所有三个属性。如何使billing_address可选?如果并非所有billing_address属性都被填写,似乎react-jsonschema-form应该只提交address。这里是react-jsonschema-form游乐场的link。 / p>

{
  "definitions": {
    "address": {
      "type": "object",
      "properties": {
        "street_address": {
          "type": "string"
        },
        "city": {
          "type": "string"
        },
        "state": {
          "type": "string"
        }
      },
      "required": [
        "street_address",
        "city",
        "state"
      ]
    }
  },
  "type": "object",
  "properties": {
    "billing_address": {
      "title": "Billing address",
      "$ref": "#/definitions/address"
    },
    "shipping_address": {
      "title": "Shipping address",
      "$ref": "#/definitions/address"
    }
  },
  "required": [
    "shipping_address"
  ]
}

2 个答案:

答案 0 :(得分:1)

您可以使用dynamic架构依赖关系来有条理地显示和要求帐单邮寄地址。这与拥有可选对象不同,但如果您愿意拥有稍微不同的用户体验,那么似乎就足够了。这是react-jsonschema-form游乐场的link。在我看来,最好查看禁用实时验证(页面右上角有一个复选框)。

{
  "definitions": {
    "address": {
      "type": "object",
      "properties": {
        "street_address": {
          "type": "string"
        },
        "city": {
          "type": "string"
        },
        "state": {
          "type": "string"
        }
      },
      "required": [
        "street_address",
        "city",
        "state"
      ]
    }
  },
  "type": "object",
  "properties": {
    "different_addresses": {
      "title": "My billing address is different than my shipping address.",
      "type": "boolean",
      "default": false
    },
    "shipping_address": {
      "title": "Shipping address",
      "$ref": "#/definitions/address"
    }
  },
  "required": [
    "shipping_address"
  ],
  "dependencies": {
    "different_addresses": {
      "oneOf": [
        {
          "properties": {
            "different_addresses": {
              "enum": [
                false
              ]
            }
          }
        },
        {
          "properties": {
            "different_addresses": {
              "enum": [
                true
              ]
            },
            "billing_address": {
              "title": "Billing address",
              "$ref": "#/definitions/address"
            }
          },
          "required": [
            "billing_address"
          ]
        }
      ]
    }
  }
}

答案 1 :(得分:0)

我的问题与您的JSON架构有关。

我需要针对依赖项定位父对象的“孙子”。 这可能吗?如果“different_addresses”是对象。

例如

  "dependencies": {
   "different_addresses": {
    "properties": {
     "OTHER_FIELD" : {
      "oneOf": [
        {
         "properties": {
          "different_addresses": {
           "properties": {
            "OTHER_FIELD" : {
             "enum": [
               false
             ]
            }
           }
          }
         }