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.

  1. anyOf
  2. oneOf
  3. allOf

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"}
    }
  ]
}

["a", 1, 0, 2] - valid (one subschema matched)

["a", 0, "ok", 2] - valid (two subschemas matched)

["a", "b"] - invalid (no subschema matched)

[] - invalid (no subschema matched)

Please pay attention when using anyOf! You can 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
      }
    }
  ]
}

[1, 2, 3] - valid

[-1, -2, -3] - valid

[0, -0, 0.0] - valid

[-1, 1] - invalid (two subschemas matched)

[-1, 0] - invalid (two subschemas matched)

[1, 0] - invalid (two subschemas matched)

[-1, 0, 1] - invalid (three subschemas matched)

[] - invalid (no subschema matched)

Please pay attention when using oneOf! You can 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"}
  ]
}

"abc" - valid

"ab" - valid

2 - valid

[1, 2, 3] - valid

"a" - invalid (length is 1)

"Ab" - invalid (must start with a)

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

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