1
votes

I got the below schema from http://json-schema.org/examples.html, i want to know if the required keyword can only come at the top level. or it can also come within the properties if there is a property of type object.I could not find any thing related to this in the specification http://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.4.3.

{
    "title": "Example Schema",
    "type": "object",
    "properties": {
        "firstName": {
            "type": "string"
        },
        "lastName": {
            "type": "string"
        },
        "age": {
            "description": "Age in years",
            "type": "integer",
            "minimum": 0
        }
    },
    "required": ["firstName", "lastName"]
}

So the below example is a valid schema

{  
   "title":"Example Schema",
   "type":"object",
   "properties":{  
      "firstName":{  
         "type":"string"
      },
      "lastName":{  
         "type":"string"
      },
      "age":{  
         "type":"object",
         "properties":{  
            "minAge":{  
               "type":"number"
            },
            "maxAge":{  
               "type":"number"
            },
            "required":[  
               "minAge",
               "maxAge"
            ]
         }
      }
   },
   "required":[  
      "firstName",
      "lastName"
   ]
}
3
Your nested required is in the wrong place. It needs to be a peer of properties, not a child. You got it right in the top level, so I'm sure this was just typo.Jason Desrosiers

3 Answers

1
votes

4.4 Keywords with the possibility to validate container instances (arrays or objects) only validate the instances themselves and not their children (array items or object properties).

So I see that yes, you can have those on any level but the validation should be only consider on the same level as required

0
votes

The required keyword can be present in any schema. This is true of all schema keywords.

(There is a special-case for the meta-keyword $schema, for which it is advisable to only have in the top level)

0
votes

Yes, required is a valid keyword in any schema. There are no restrictions for nested schemas.

To use your example, the following is a valid schema and will validate the way you want it to.

{  
    "title": "Example Schema",
    "type": "object",
    "properties": {  
        "firstName": {  
            "type": "string"
        },
        "lastName": {  
            "type": "string"
        },
        "age": {  
            "type": "object",
            "properties": {  
                "minAge": {  
                    "type": "number"
                },
                "maxAge": {  
                    "type": "number"
                }
            },
            "required": [  
                "minAge",
                "maxAge"
            ]
        }
    },
    "required": [  
        "firstName",
        "lastName"
    ]
}