Mike Silverman
Mike Silverman

Reputation: 85

Require one of several other properties in a JSON Schema

Inexperienced JSON Schema user here. I have a JSON Schema that I would like to check for the following cases. Most I've figured out, but one just isn't working out.

I could have properties A, B, C, D, E, F. Some rules:

  1. If E exists, it needs F, and vice versa. (Got it)
  2. If A, B, or C exist, they need D. (Got it)
  3. D or F must appear (Got it)
  4. If D appears, it must have either A, B, or C. (Preferably only one of A, B, or C, but I'll handle that downstream if needed.) (This one is eluding me.)

Here's the schema:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "patternProperties": {
    "^*": {
      "type": "object",
      "properties": {
        "A": {
          "type": [ "string", "null" ]
        },
        "B": {
          "type": [ "string", "null" ]
        },
        "C": {
          "type": [ "string", "null" ]
        },
        "D": {
          "type": [ "string", "null" ]
        },
        "E": {
          "type": [ "string", "null" ]
        },
        "F": {
          "type": [ "string", "null" ]
        }
      },
      "dependentRequired": {
        "E": [ "F" ],
        "F": [ "E" ],
        "A": [ "D" ],
        "B": [ "D" ],
        "C": [ "D" ]
      },      
      "oneOf": [
          { "required": [ "D" ] },
          { "required": [ "F" ] }
      ]
    }
  }
}

The validation should fail if you only submit "D." But in this schema it will pass.

I've tried playing around with if/thens, anyOfs, ... just not able to get Rule 4 working. Some advice would be helpful!! Thank you in advance.

Upvotes: 1

Views: 1136

Answers (1)

Ether
Ether

Reputation: 54014

The required keyword validates to true when the property exists, and is false when it does not. Therefore it can be used in if and then clauses:

"if": {
  "required": ["D"]
},
"then": {
  "oneOf": [
    { "required": ["A"] },
    { "required": ["B"] },
    { "required": ["C"] }
  ]
}

PS. you can shorten "patternProperties": { "^*": { ... } } to "additionalProperties": { ... } (and ^* isn't a valid regex anyway, so your validator really ought to be erroring about that).

Upvotes: 3

Related Questions