1
votes

I am trying to figure out if there is a way to validate that a specific JSON instance has no additional fields outside of the ones declared in the schema.

Let s take this schema as an example:

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "title": "Client",
    "type": "object",
    "properties": {
        "name": {
            "type": "string"
        },
        "email": {
            "type": "string"
        },
        "isActive": {
            "type": "boolean"
        }
    },
    "required": []
}

I would like to enforce that any JSON of this "type" can only have name, email and isActive. If the following JSON is validated I would like validation to fail:

{
   "name": "John",
   "email": "[email protected]",
   "isActive": true,
   "extrafield": 123
}

I am using json-schema-validator to execute the validation, but I have a feeling that more than an implementation issue/assumption with the specific validator I am using, it is my JSON schema that is not enforcing preventing undefined fields.

How can I achieve that? Thanks

1

1 Answers

2
votes

What you're looking for is additionalProperties.

The value of "additionalProperties" MUST be a valid JSON Schema.

This keyword determines how child instances validate for objects, and does not directly validate the immediate instance itself.

Validation with "additionalProperties" applies only to the child
values of instance names that do not match any names in "properties", and do not match any regular expression in "patternProperties".

For all such properties, validation succeeds if the child instance validates against the "additionalProperties" schema.

https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.5.6

To translate: The value of a key in properties, which is a schema, is applied to the object of the instance of the keys value.

Any properties of your instance object which are not validated by properties (nor by patternProperties), are then evaluated by additionalProperties.

The value of any schema can be false, which assers validation failure, so you want to add additionalProperties: false to your schema.

Note however, that additionalProperties cannot "see through" other applicator keywords like oneOf, and is only applicable based on properties and patternProperties.

(draft-8 will introduce a new key word, unevaluatedProperties to provide this functionality, but that version is not published at current).