如何用JSON Schema验证包含指定必填项的字符串数组?
I get where you're stuck—your current schema does a good job restricting array elements to your allowed enum and ensuring no duplicates, but it doesn't enforce that the four mandatory values (uuid, template, createdOn, updatedOn) are always present. The required keyword works for object properties, not array elements, so we need a different approach here.
Solution: Use allOf + contains to Mandate Required Items
To make sure your array includes all four mandatory values while still sticking to your allowed enum, you can combine the allOf keyword with multiple contains rules. Each contains check verifies one mandatory value is present, and allOf ensures all these checks pass together.
Here's the revised JSON Schema:
{ "$schema": "http://json-schema.org/draft-07/schema#", "$id": "56544e3c-e197-4602-8457-2c01dc6b12c5", "title": "The Root Schema", "type": "object", "additionalProperties": false, "required": ["attributes"], "properties": { "attributes": { "type": "array", "uniqueItems": true, "items": { "type": "string", "enum": ["uuid", "template", "createdOn", "updatedOn", "fields", "elements"] }, "allOf": [ { "contains": { "const": "uuid" } }, { "contains": { "const": "template" } }, { "contains": { "const": "createdOn" } }, { "contains": { "const": "updatedOn" } } ] } } }
Breakdown of Key Changes:
allOf: Wraps four separate validation rules, all of which must pass for the array to be valid.contains+const: Each entry checks that the array includes exactly the specified mandatory string.constguarantees an exact match, whilecontainsconfirms the value appears at least once in the array.- We keep your original constraints:
uniqueItems: true(prevents duplicate entries) anditems.enum(limits array elements to your allowed list).
Validation Results:
- Valid instances (will pass):
{ "attributes": ["uuid", "template", "createdOn", "updatedOn"] }{ "attributes": ["uuid", "template", "createdOn", "updatedOn", "fields", "elements"] } - Invalid instance (will fail, missing
updatedOn):{ "attributes": ["uuid", "template", "createdOn", "fields", "elements"] }
This setup hits both your requirements: it ensures all mandatory values are present, and only allows the enum values you specified in the array.
内容的提问来源于stack exchange,提问作者Chris

