4

I want to add conditionally required based on value of some other property. 'companyName' and 'companyAddress' should be required only if 'isInexperienced' value is false.

Schema

{
  "type": "object",
  "properties": {
    "previous_employment_section": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "companyAddress": {
            "type": "string"
          },
          "companyName": {
            "type": "string"
          }
        },
        "if": {
          "#/properties/isInexperienced": {
            "const": false
          }
        },
        "then": {
          "required": [
            "companyName",
            "companyAddress"
          ]
        }
      }
    },
    "isInexperienced": {
      "type": "boolean"
    }
  }
}

Data

{
  "previous_employment_section": [],
  "isInexperienced": true
}

2 Answers2

3

I do not fully understand the intention of your original schema, but how about this one?

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "type": "object",
    "properties": {
        "previous_employment_section": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "companyAddress": {
                        "type": "string"
                    },
                    "companyName": {
                        "type": "string"
                    }
                }
            }
        },
        "isInexperienced": {
            "type": "boolean"
        }
    },
    "if": {
        "properties": {
            "isInexperienced": {
                "const": false
            }
        }
    },
    "then": {
        "properties": {
            "previous_employment_section": {
                "items": {
                    "required": [
                        "companyName",
                        "companyAddress"
                    ]
                },
                "minItems": 1
            }
        }
    }
}
leadpony
  • 214
  • 2
  • 4
1

It is not possible. We need to have “if” on a higher level, “properties” can be nested. Leadpony's method can be used.