I have to following JSON Schema:
{
"type": "object",
"required": [
"type",
"title"
],
"properties": {
"type": {
"enum": [
"journal",
"book",
"generic"
]
},
"title": {
"type": "string",
"minLength": 1,
"maxLength": 500
}
}
}
According to that schema, the following object is valid:
{type: 'journal', title: 'foo'}
And this one isn't:
{type: 'qux', title: ''}
Is there a way I can reuse subsets of that schema so that I can also validate types and titles individually?
e.g. (in pseudo code)
const Ajv = require('ajv');
const ajv = new Ajv;
ajv.addSchema(/* see schema above */);
const validate_document = ajv.compile(/* see schema above */);
const validate_type = ajv.compile(/* reuse corresponding subset */);
const validate_title = ajv.compile(/* reuse corresponding subset */);
validate_document({type: 'qux', title: ''}); // false
validate_type('qux'); // false
validate_title(''); // false
I settled on this solution which allows me to keep the schema "integrity" (I don't need to split it into smaller parts so that it remains easy to read and understand). All I needed to do is to set
$id
keys on the relevant schemas:Ajv allows you to reference a schema by its id in
Ajv#getSchema
which compiles a schema into a validation function: