jsonjsonschema

JSON Schema 2019-09 - Conditional Required


My schema has one enum value type. It can have Client or Corporate. I need a way to fit in a validation when, if the "type": "Client" only then another field font is required.

JSON Body

{
  "type": "Client",
  "font": "Small",
  "occupation": "Super"
}

JSON Schema

{
    "$schema": "https://json-schema.org/draft/2019-09/schema",
    "$id": "http://example.com/example.json",
    "title": "Root Schema",
    "type": "object",
    "default": {},
    "required": ["type", "occupation"],
    "properties": {
        "type": {
            "type": "string",
            "enum": ["Client", "Corporate"]
        },
        "font": {
            "type": "string"
        },
        "occupation": {
            "type": "string"
        }
    },
    "examples": [
        {
            "type": "Client",
            "font": "Large",
            "occupation": "Super"
        }
    ],
    "oneOf": [
        {
            "properties": {
                "type": {
                    "enum": ["Client"]
                }
            }
        },
        {
            "required": ["font"]
        }
    ]
}

I've tried with oneOf however it is not working.

Edit: Fixed type


Solution

  • Try if and then keywords instead of oneOf?

    "if": {
      "properties": {
        "type": {
          "const": "Client"
        }
      },
      "required": ["type"]
    },
    "then": {
      "required": ["font"]
    }
    

    You can checkout the official doc.