0

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.

Sreekar Mouli
  • 1,313
  • 5
  • 25
  • 49

1 Answers1

0

The library you're using only supports draft-04 of the specification.

if / then / else wasn't added till draft-07.

Relequestual
  • 11,631
  • 6
  • 47
  • 83
  • Which version is 'draft-07'? – Sreekar Mouli Nov 24 '20 at 12:29
  • `jsonschema` is an npm package. It looks like it only supports SOME of draft-04. If you want `draft-07` support, you'll need to look for a new library. – Relequestual Nov 24 '20 at 12:30
  • 1
    @SreekarMouli if you are stuck with draft-04, you can use the Implication Pattern to get the same behavior as `if`/`then`, https://stackoverflow.com/questions/38717933/jsonschema-attribute-conditionally-required/38781027#38781027. But, you're better off choosing a different JSON Schema implementation that supports more recent drafts. Two options are ajv and hyperjump/json-schema. – Jason Desrosiers Nov 24 '20 at 23:22