conditionally validate a json schema based on a parent property or parent schema

I have the following json schema

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "title": "MySchema",
  "required": ["environment", "datacenter"],
  "properties": {
    "environment": {
      "type": "string",
      "title": "environment",
      "enum": ["DEV", "STG", "PROD"]
    },
    "datacenter": {
      "type": "object",
      "title": "datacenter",
      "properties": {
        "value": {
          "$ref": "#/definitions/datacenter"
        }
      }
    }
  },
  "definitions": {
    "datacenter": {
      "type": "string",
      "enum": [ "devDC1", "devDC2", "stgDC1", "stgDC2", "prodDC1", "prodDC2" ]
    }
  }
}

and here is how it could be simply used

{
    "$schema": "http://localhost/schemas/v3/env.json",
    "environment": "DEV",
    "datacenter": {
        "value": "devDC1"
    }
}

what I'm trying to do is something like

if the environment is set to DEV, then I should only be able to select devDC1, devDC2 for the value of the datacenter attribute, and same if i select STG for environment then stgDC1, stgDC2 are allowed, and same for PROD

note that "$ref": "#/definitions/datacenter" in my schema is actually referencing another file


Solution 1:

You can use if+allOf (see the second example here), e.g.:

  "allOf": [
    {
      "if": {"properties": {"environment": {"const": "DEV"}}},
      "then": {"properties": {"datacenter": {"properties": {"value": {"pattern": "^dev"}}}}}
    },
    {
      "if": {"properties": {"environment": {"const": "STG"}}},
      "then": {"properties": {"datacenter": {"properties": {"value": {"pattern": "^stg"}}}}}
    },
    {
      "if": {"properties": {"environment": {"const": "PROD"}}},
      "then": {"properties": {"datacenter": {"properties": {"value": {"pattern": "^prod"}}}}}
    }
  ]

Note that in addition to that you will need to add "required": ["value"] into /properties/datacenter (otherwise "datacenter": {} would also be accepted irrespectively to the environment).