1

Using JSON Schema, how can I specify that property bar is required when property foo (a boolean) is set to true?

I've tried the following:

{
  "type": "object",
  "properties": {
    "foo": { "type": "boolean" },
    "bar": { "type": "string" }
  },
  "if": {
    "properties": {
      "foo": { "boolean": true }
    },
    "required": ["foo"]
  },
  "then": { "required": ["bar"] }
}

However, this fails to validate:

{
  "foo": false
}

because it seems bar is still required despite foo being false:

Message:
    Required properties are missing from object: bar.
Schema path:
    #/then/required

I've also tried this:

{
  "type": "object",
  "properties": {
    "foo": { "type": "boolean" },
    "bar": { "type": "string" }
  },
  "if": {
    "properties": {
      "foo": { "const": "true" }
    },
    "required": ["foo"]
  },
  "then": { "required": ["bar"] }
}

But this accepts the following JSON, which should be considered invalid:

{
  "foo": true
}

I've already seen this answer, but it uses type string for foo, which works fine. I need foo to be boolean.

How can I stipulate that bar is required when foo is true?

Kent Boogaart
  • 175,602
  • 35
  • 392
  • 393

1 Answers1

1

You were SO CLOSE to getting this right.

Your use of const was correct, but the value is a string as opposed to a boolean value. You want...

"foo": { "const": true }

Live demo

Relequestual
  • 11,631
  • 6
  • 47
  • 83