Multiple subschemas

Keywords for applying multiple subschemas

It is a common practice to validate something against multiple subschemas, and the following keywords will help you combine subschemas into one validator.

Validation keywords

The following keywords are supported by any instance type, and are evaluated in the presented order. All keywords are optional.

anyOf

An instance is valid against this keyword if is valid against at least one schema defined by the value of this keyword. The value of this keyword must be an array of valid json schemas (objects or booleans).

Please note that Opis JSON Schema will stop checking other subschemas once a subschema validates the instance. This is done for performance reasons.

{
  "type": "array",
  "anyOf": [
    {
      "contains": {"const": 0}
    },
    {
      "contains": {"const": "ok"}
    }
  ]
}
Input Status
["a", 1, 0, 2] valid - one subschema match
["a", 0, "ok", 2] valid - two subschemas match
["a", "b"] invalid - no subschema match
[] invalid - no subschema match

Please pay attention when using anyOf! You could unintentionally write schemas that never validate!

{
  "type": "string",
  "anyOf": [
    {"const": 0},
    {"const": 1}
  ]
}

oneOf

An instance is valid against this keyword if is valid against exactly one schema defined by the value of this keyword. The value of this keyword must be an array of valid json schemas (objects or booleans).

Please note that Opis JSON Schema will stop checking other subschemas once two subschemas validate the instance. This is done for performance reasons.

{
  "type": "array",
  "items": {
    "type": "number"  
  },
  "oneOf": [
    {
      "items": {
        "exclusiveMinimum": 0
      }
    },
    {
      "items": {
        "exclusiveMaximum": 0
      }
    },
    {
      "items": {
        "const": 0
      }
    }
  ]
}
Input Status
[1, 2, 3] valid
[-1, -2, -3] valid
[0, -0, 0.0] valid
[-1, 1] invalid - two subschemas match
[-1, 0] invalid - two subschemas match
[1, 0] invalid - two subschemas match
[-1, 0, 1] invalid - three subschemas match
[] invalid - no subschema match

Please pay attention when using oneOf! You could unintentionally write schemas that never validate!

{
  "oneOf": [
    {"const": 0},
    {"enum": [0, 1, 2]}
  ]
}

allOf

An instance is valid against this keyword if is valid against all schemas defined by the value of this keyword. The value of this keyword must be an array of valid json schemas (objects or booleans).

{
  "allOf": [
    {"minLength": 2},
    {"pattern": "^a"}
  ]
}
Input Status
"abc" valid
"ab" valid
2 valid
[1, 2, 3] valid
"a" invalid - length is 1
"Ab" invalid - must start with an a

Please pay attention when using allOf! You could unintentionally write schemas that never validate!

{
  "allOf": [
    {"type": "string"},
    {"type": "number"}
  ]
}