Applying subschemas conditionally

Sometimes you need to conditionally apply a subschema or to negate the validation result. The following keywords help you do that.

Validation keywords

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

  1. not
  2. if-then-else

not

An instance is valid against this keyword if is not valid against the schema defined by the value of this keyword. The value of this keyword must be a valid json schema (object or boolean).

{
  "not": {
    "type": "string"
  }
}

-2.3 - valid

true - valid

null - valid

{"a": "test"} - valid

[1, 2, 3] - valid

"some string" - invalid

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

{
  "type": "string",
  "not": {
    "type": "string"
  }
}

if-then-else

This is a conditional structure containing three keywords: if, then and else. Every keyword value must be a valid json schema (object or boolean). If the if keyword is not present the then and else keywords are ignored, but when the if keyword is present at least then or else should also be present (both can be at the same time). The instance is valid against this keyword in one of the following cases:

  • the if keyword validates the instance and the then keyword also validates it
  • the if keyword doesn’t validate the instance but the else keyword validates it.

As a best practice, please place these keywords in the same order as defined here and do not add other keywords between them.

{
  "if": {
    "type": "string"
  },
  "then": {
    "minLength": 3
  },
  "else": {
    "const": 0
  }
}

"abc" - valid (string with length = 3)

"abcd" - valid (string with length = 4)

0 - valid

-0.0 - valid

"ab" - invalid (string with length = 2)

1 - invalid (not a string and not 0)

["abc"] - (not a string and not 0)

{
  "if": {
    "type": "string"
  },
  "then": {
    "minLength": 3
  }
}

"abc" - valid (string with length = 3)

"abcd" - valid (string with length = 4)

"ab" - invalid (string with length = 2)

0 - invalid (not a string)

["abc"] - (not a string)

{
  "if": {
    "type": "string"
  },
  "else": {
    "const": 0
  }
}

"abc" - valid (string)

"" - valid (string)

0 - valid ()

-0.0 - valid ()

1 - invalid (not a string and not 0)

["abc"] - (not a string and not 0)