2

I need to make a schema that expects a property to exist if another property has a certain value.

{"handleFailure":"redirect","redirectUrl":"http://something.com"}

and

{"handleFailure":"reject"}

should both be valid, but

{"handleFailure:"redirect"}

should not be valid due to the redirectUrl property not being present.

I have tried to make a top level oneOf with the two schemas like so

{
  "type": "object",
  "additionalProperties": false,
  "oneOf": [
    {
      "properties": {
        "handleFailure": {
          "type": "string",
          "enum": [
            "redirect"
          ]
        },
        "redirectUrl": {
          "type": "string",
          "format": "uri"
        }
      }
    },
    {
      "properties": {
        "handleFailure": {
          "type": "string",
          "enum": [
            "reject"
          ]
        }
      }
    }
  ]
}

but I get an error about the properties not being defined. Is there a way to do this?

Alex Haynes
  • 322
  • 3
  • 16

1 Answers1

2

Insert the "additionalProperties": false flag into the sub schemas to prevent those objects having additional properties.

{
  "type": "object",
  "additionalProperties": false,
  "oneOf": [
    {
      "additionalProperties": false,
      "properties": {
        "handleFailure": {
          "type": "string",
          "enum": [
            "redirect"
          ]
        },
        "redirectUrl": {
          "type": "string",
          "format": "uri"
        }
      }
    },
    {
      "additionalProperties": false,
      "properties": {
        "handleFailure": {
          "type": "string",
          "enum": [
            "reject"
          ]
        }
      }
    }
  ]
}
bhspencer
  • 13,086
  • 5
  • 35
  • 44