user979189
user979189

Reputation: 1308

How to write complex conditional validation in JSON schema?

Below is the sample JSON schema. I need to implement this validation -

If property1 has a value of "abc" and property2 has "abc111" in the list of provided values, then subProperty1 is mandatory inside property3

{
  "type": "object",
  "additionalProperties": false,
  "properties": {
    "property1": {
      "type": "string"
    },
    "property2": {
      "type": "array",
      "items": {
        "type": "string"
      }
    },
    "property3": {
      "type": "object",
      "properties": {
        "subProperty1": {
          ...
        },
        "subProperty2": {
          ...
        },
      }
    }
  }
}

I tried to implement it using this JSON -

  "if": {
    "properties": {
      "property1": {
        "const": "abc"
      },
      "property2": {
        "contains": {
          "properties": {
            "items": {
              "const": "abc111"
            }
          }
        }
      }
    }
  },
  "then": {
    "dependentSchemas": {
      "property1": {
        "required": [ "property3" ],
        "message": "Error - Missing property3 with subProperty1",
        "properties": {
          "property3": {
            "required": [ "subProperty1" ]
          }
        }
      }
    }
  }

But this doesnt work as expected. Could someone please help me fix the conditional logic?

Upvotes: 0

Views: 400

Answers (1)

Ether
Ether

Reputation: 53996

It's hard to say without knowing in what way things aren't working as expected. But you may be missing a required keyword in your if clause -- in order to ensure that property1 really is present. (The properties keyword evaluates to true if the property isn't present at all.) Then you would also need a required: ["property3"] in your then clause.

Also, you don't need dependentSchemas at all -- you are adding a dependency on property1, but that's already in the if clause so it's redundant.

Upvotes: 1

Related Questions