I have an array that contains strings, such as:
[ 'foo', 'bar' ]
The possible values are limited. For example, valid values are foo
, bar
, and baz
.
Now the array shall be valid when it contains only values that are valid, no value more than once, but it can have an arbitrary number of values.
Examples for valid arrays would be [ 'foo' ]
, [ 'foo', 'bar' ]
, and [ 'bar', 'baz' ]
. Examples for invalid arrays would be []
, [ 'foo', 'foo' ]
, and [ 'bar', 'something-else' ]
.
How can I do this validation using JSON schema? So far, I have figured out the array
type which provides the minItems
and the uniqueItems
properties. What I could not yet figure out is: How to allow multiple (but only valid) values? I know that there is enum
, but this only allows a single value, not multiple ones.
Can anybody help?
PS: Just in case it matters, I'm using the ajv module with Node.js to run the validation.
Spelling out the solution more clearly:
{
"type": "array",
"items": {
"type": "string",
"enum": [ "foo", "bar", "baz" ]
},
"uniqueItems": true,
"minItems": 1
}
See: https://spacetelescope.github.io/understanding-json-schema/reference/array.html
Okay, I got it by myself…
You need to provide the items
property as well, and then for each item define that it needs to be of type: 'string'
and its value to be an enum: [ 'foo', 'bar', 'baz' ]
.
This way you ensure that each single items is a string with a valid value, and then you enforce this for the entire array ☺️
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With