Search code examples
jsonschemajson-schema-validator

Json Schema - Define dependentRequired between properties in different objects


How is it possible to use the dependantRequired to bind two properties that are in different objects?

for example in the following schema:

{
    "$schema": "https://json-schema.org/draft/2019-09/schema",
    "$id": "https://test.com/account",
    "$vocabulary": {
        "https://json-schema.org/draft/2019-09/vocab/core": true,
        "https://json-schema.org/draft/2019-09/vocab/applicator": true,
        "https://json-schema.org/draft/2019-09/vocab/validation": true,
        "https://json-schema.org/draft/2019-09/vocab/meta-data": true,
        "https://json-schema.org/draft/2019-09/vocab/format": false,
        "https://json-schema.org/draft/2019-09/vocab/content": true
    },
    "$recursiveAnchor": true,
    "title": "Core and Validation specifications meta-schema",
    "properties": {
      "bearer": {
                  "$anchor": "bearer_anchor",
                    "type": "string"
                },
        "profile": {
            "type": "object",
            "properties": {
                "email": {
                  "type":"string"
                },
                "password": {
                  "type":"string"
                },
                "number": {
                    "type": "number"
                },
                "street_name": {
                    "type": "string"
                },
                "street_type": {
                    "enum": [
                        "Street",
                        "Avenue",
                        "Boulevard"
                    ]
                }
            },
            "dependentRequired": {
                "email": [{"$ref": "https://test.com/account#bearer_anchor"}],
                "password": [{"$ref": "https://test.com/account#bearer_anchor"}],
            }, 
            "additionalProperties": false
        }
    },
    "additionalProperties": false
}

I am trying to define that profile\email and profile\password must be provided with the property bearer.

I did try among many things to use the $ref for an absolute path as you can see.


Solution

  • You won't be able to use dependentRequired for this because that keyword only works within the same schema. However, you can use if/then.

    This,

    "dependentRequired": {
      "a": ["b"]
    }
    

    is effectively syntactic sugar for the pattern,

    "if": { "required": ["a"] },
    "then": { "required": ["b"] }
    

    This is more verbose, but it allows for more expressiveness. We can expand this to check for the profile/email property.

    "if": {
      "properties": {
        "profile": { "required": ["email"] }
      }
      "required": ["profile"]
    },
    "then": { "required": ["bearer"] }