I wanted a JSON schema that could have 3 fields: num, key1, and key2. Both num and key1 are mandatory fields. The field key2 is mandatory ONLY WHEN the key1 was provided a value of 'abc'. Here is the schema that I have created:
schema = {
type: 'object',
additionalProperties: false,
properties: {
num: {
type: 'number',
minimum: 1,
maximum: 5
},
key1: {
type: 'string',
enum: ['abc', 'def']
}
},
required: ['num', 'key1'],
if: {
properties: {
key1: {
const: 'abc'
}
}
},
then: {
properties: {
key2: {
type: 'string',
required: true
}
}
}
};
Here is the instance that I want to validate against the schema using npm module jsonscehma ("jsonschema": "^1.2.0"):
instance = {
num: 1,
key1: 'abc'
};
var Validator = require('jsonschema').Validator;
var v = new Validator();
console.log(v.validate(instance, schema));
My expectation here is that, since the value of key1 is 'abc', this should ideally throw an error saying
mandatory field "key2" is missing
But, there is no such error in this case.
Also, if I provide key2 in the instance, I am getting
additionalProperty "key2" exists in instance when not allowed
even though, key1 is 'abc'.
Please specify if I have missed anything here.