Sumeet Ambastha
Sumeet Ambastha

Reputation: 15

How to include validations for key as well as value in a json schema

I need to add validations for a property as well as a value in json schema.

I tried to use the below schema but none of the validations work :

{
    "$schema": "http://json-schema.org/draft-06/schema#",
    "type": "object",
    "additionalProperties": false,
    "minProperties": 1,
    "properties": {
        "add": {
            "type": "object",
            "patternProperties": {
                "^VOF979[0-9]{11}-NDG[0-9]{2}$": {
                    "description": "Some description",
                    "type": "string",
                    "maxLength": 2
                }
            }
        }
    }
}

I used below json data and all the validations passes although the key and value both are wrong :

{
    "add": {"VOF98999990005235-NDG01": "121"}
}

Upvotes: 0

Views: 1105

Answers (2)

Relequestual
Relequestual

Reputation: 12295

JSON Schema is constraints based.

patternProperties applies its value schema to the instance location based on the key match (in this case, regex match).

It does not prohibit additional keys in the object.

If you want to prevent additional keys, you need to specify so.

To do this, you need "additionalProperties": false.

Upvotes: 1

Biswa Soren
Biswa Soren

Reputation: 325

Do not allow additional properties to keep strict validation

{
  "$schema": "http://json-schema.org/draft-06/schema#",
  "type": "object",
  "properties": {
    "add": {
      "type": "object",
      "patternProperties": {
                "^VOF979[0-9]{11}-NDG[0-9]{2}$": {
                    "description": "Some description",
                    "type": "string",
                    "maxLength": 2
                }
            },
      "additionalProperties": false // This One
    }
  },
  "additionalProperties": false,
  "minProperties": 1
}

Reference to Docs Have a look at this

Upvotes: 0

Related Questions