Generic keywords
Generic validation keywords
The type
, const
, and enum
generic keywords, allow you to validate JSON data,
by checking if its value, or its type, matches a given value or type.
The keywords can be used with all JSON types and are evaluated in the order on which they are presented below.
All these keywords are optional.
type
The type
keyword specifies the type of data that the schema is expecting to validate.
This keyword is not mandatory and the value of the keyword must be a string,
representing a valid data type, or an array of strings, representing a
valid list of data types.
{
"type": "string"
}
Input | Status |
---|---|
"some text" |
valid |
"" |
valid - empty string |
12 |
invalid - is integer/number |
null |
invalid - is null |
When specifying multiple types, their order is irrelevant to the validation process, but you should make sure that a data type is specified only once.
{
"type": ["object", "null"]
}
Input | Status |
---|---|
{"a": 1} |
valid - is object |
null |
valid - is null |
"1, 2, 3" |
invalid - is string |
[{"a": 1}, {"b": 2}] |
invalid - is array |
{
"type": ["number", "string", "null"]
}
Input | Status |
---|---|
-10.5 |
valid - is number |
"some string" |
valid - is string |
null |
valid - is null |
false |
invalid - is boolean |
{"a": 1} |
invalid - is object |
[1, 2, 3] |
invalid - is array |
const
An instance validates against this keyword if its value equals to the value of this keyword. The value of this keyword can be anything.
{
"const": "test"
}
Input | Status |
---|---|
"test" |
valid |
"Test" |
invalid |
"tesT" |
invalid |
3.4 |
invalid |
{
"const": {
"a": 1,
"b": "2"
}
}
Input | Status |
---|---|
{"a": 1, "b": "2"} |
valid |
{"b": "2", "a": 1} |
valid |
{"a": 1, "b": "2", "c": null} |
invalid |
5.10 |
invalid |
enum
An instance validates against this keyword if its value equals can be found in the items defined by the value of this keyword. The value of this keyword must be an array containing anything. An empty array is not allowed.
{
"enum": ["a", "b", 1, null]
}
Input | Status |
---|---|
"a" |
valid |
"b" |
valid |
1 |
valid |
null |
valid |
"A" |
invalid |
-1 |
invalid |
false |
invalid |
["a", "b", 1, null] |
invalid |