minContains and maxContains

Previously, we learned how to use the contains keyword to ensure that an array contains at least one element that matches a specific subschema.

However, there are scenarios where we need to ensure that an array contains a specific number of elements that match a subschema.

You can use the minContains and maxContains keywords along with contains to specify the minimum and maximum number of elements that an array must contain to be valid.

Example

The following example demonstrates how to use the minContains and maxContains keywords to ensure that an array contains exactly 2 elements that are less than 10.

1{
2  "type": "array",
3  "contains": {
4    "type": "number",
5    "maximum": 10
6  },
7  "minContains": 2,
8  "maxContains": 2
9}

Task

1{
2  "name": "John Doe",
3  "age": 30,
4  "workedHours": [9, 10, 8, 11]
5}

Our employee has field called worked hours. We want to ensure that the workedHours array contains at least 2 elements that are greater than or equal to 8 and less than or equal 12. Modify the schema given to you in the side editor to apply this constraint.

Loading...
Output
Please click the button or use
Shift+Enter
to view the output