Conditional subschemas
Keywords for applying conditional subschemas
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.
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"
}
}
Input | Status |
---|---|
-2.3 |
valid |
true |
valid |
null |
valid |
{"a": "test"} |
valid |
[1, 2, 3] |
valid |
"some string" |
invalid |
Please pay attention when using not
!
You could unintentionally 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 thethen
keyword also validates it - the
if
keyword doesn’t validate the instance but theelse
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
}
}
Input | Status |
---|---|
"abc" |
valid - string of length 3 |
"abcd" |
valid - string of length 4 |
0 |
valid |
0.0 |
valid |
"ab" |
valid - string of length 2 |
1 |
invalid - not a string and not 0 |
["abc"] |
invalid - not a string and not 0 |
{
"if": {
"type": "string"
},
"then": {
"minLength": 3
}
}
Input | Status |
---|---|
"abc" |
valid - string of length 3 |
"abcd" |
valid - string of length 4 |
"ab" |
invalid - string of length 2 |
0 |
invalid - not a string |
["abc"] |
invalid - not a string |
{
"if": {
"type": "string"
},
"else": {
"const": 0
}
}
Input | Status |
---|---|
"abc" |
valid |
"" |
valid |
0 |
invalid |
-0.0 |
invalid |
1 |
invalid - not a string and not 0 |
["abc"] |
invalid - not a string and not 0 |