Naqeeb
Naqeeb

Reputation: 245

JSON Schema: Require properties on an optional object type

I have defined a customer object type in my json schema:

"customer": {
    "type": "object",
    "properties": {
      "id": { "type": "string" },
      "first_name": { "type": "string" },
      "last_name": { "type": "string"},
      "email": { "type": "string" },
      "billing_address": { "$ref": "#\/definitions\/street_address" },
      "shipping_address": { "$ref": "#\/definitions\/street_address" },
    },
    "required": [ "id", "first_name", "last_name", "email", "billing_address"]
  },

I would like to validate shipping_address (optional object) if it is sent and reject it if it is missing the required fields. Here is the street_address object definition:

"street_address": {
    "type": "object",
    "properties": {
      "first_name": {"type": "string" },
      "last_name": { "type": "string" },
      "address": { "type": "string" },
      "address2": { "type": "string" },
      "city": { "type": "string" },
      "state": { "type": "string" },
      "zip_code": { "type": "string"},
      "country_code": { "type": "string"},
      "phone": { "type": "string"},
      "fax": {"type": "string"}
    },
    "required": [
      "first_name",
      "last_name",
      "address",
      "city",
      "state",
      "zip_code",
      "country_code"
    ]
  },

How do I configure my JSON schema to accomplish this? When I send a shipping address now, the fields inside the object do not get validated.

Upvotes: 4

Views: 7556

Answers (1)

Jan Wy
Jan Wy

Reputation: 1569

You are using the reference "$ref": "#\/definitions\/street_address" (btw, you dont have to escape the slashes). In that case the street_address definition must be in in the same document, inside the "defintions" node. So your schema file looks like this

   {
    "$schema": "http://json-schema.org/draft-04/schema#",
    "title": "customer",
    "type": "object",
    "properties": {
      "id": { "type": "string" },
      "first_name": { "type": "string" },
      "last_name": { "type": "string"},
      "email": { "type": "string" },
      "billing_address": { "$ref": "#/definitions/street_address" },
      "shipping_address": { "$ref": "#/definitions/street_address" },
    },
    "required": [ "id", "first_name", "last_name", "email", "billing_address"],
    "definitions" : {
        "street_address" : { 
             /* here comes the street_address definition */ 
        },
        /* other entity definitions */
     }

  }

I'm using the nodejs module jayschema (see https://github.com/natesilva/jayschema) for validation, and it works fine that way.

Upvotes: 1

Related Questions