Reputation: 5123
I am using ajv
node package to validate my schemas. Supposed that a field holds an object type.
The object can have 3 properties: "A", "B", and "C"
.
How do I specify that at least one of these properties must be defined and no other properties are allowed?
Upvotes: 1
Views: 1010
Reputation: 657
Depending on if you want to disallow all other properties or just the specific other ones (if "A" is present, "B" and "C" are forbidden but "foo" is still OK) you can either use oneOf
with the additionalProperties: false
property or use not
to disallow specific properties. Example for both:
schmema:
{
"anyOf": [
{
"properties": {"A": {}},
"required": ["A"],
"additionalProperties": false
},
{
"properties": {
"B": {},
"A": { "not": {} },
"C": { "not": {} }
},
"required": ["B"],
}
]
}
Note: The pattern "not": {}
is always false
so no value for the corresponding property can ever fulfill it.
This example uses additionalProperties: false
for "A" so it matches
{
"A": 3
}
but neither
{
"A": 3,
"B": 5
}
nor
{
"A": 3,
"foo": 5
}
On the other hand, the example uses not
for the "B" case so it matches
{
"B": 3
}
and
{
"B": 3,
"foo": 5
}
but not
{
"A": 3,
"C": 5
}
Upvotes: 1
Reputation: 24399
You can use anyOf
for this constraint. The anyOf
keyword allows you to combine constraints using a boolean OR operation.
{
"anyOf": [
{ "required": ["A"] },
{ "required": ["B"] },
{ "required": ["C"] }
]
}
Upvotes: 1