React JSON Schema Dependencies

1.9k Views Asked by At

I am trying to write up a JSONSchema to be used with react-jsonschema-form, but am having trouble getting the dependencies working and in the correct order.

  "properties":{
      "condition": {
          "type":"string",
          "enum":["1","2"],
           "options": {
           "dependencies":[
              {"id":"one","value":"1"},
              {"id":"two","value":"2"}
              ]
           }
      },
      "one":{
          "id":"one",
          "type":"number"
          },
      "two":{
          "id":"two",
          "type":"string"
      },
      "misc": {
        "type": "string"
      }
  },
  "type": "object"
}

In the above, what I had hoped was for valid form data to be...

{
  "condition": "1",
  "one": 123
  "misc": "abc"
}

Or if condition is "2"...

{
  "condition": "2",
  "two": "something",
  "misc": "abc"
}

But instead the dependencies section does not seem to work as I had hoped. So both "one" and "two" can be present regardless of the condition value.

{
  "condition": "1",
  "one": 123,
  "two": "something",
  "misc": "abc"
}

How can I change the JSON Schema so that only the respective field is possible based on the "condition".

Note... order does matter in the schema provided. Please see https://rjsf-team.github.io/react-jsonschema-form/ for demos.

1

There are 1 best solutions below

0
On

You have to use oneOf operator. It take multiple dependencies, and if one of them are true, the json is valid.

Example:

"oneOf":[
    {
      "required": [
        "name",
        "dateOfBirth"
      ]
    },
    {
      "required": [
        "name",
        "age"
      ]
    }

More example can be found here.