jsonschemajsonforms

Dependency on the existence of a nested value


I can get dependencies to work with non-nested values (top-level in the schema), but I would like for a dependency to be dependent on a property which is nested within an object definition.

const schema = {
  type: "object",
  properties: {
    start: {
      type: "object",
      properties: {
        time: {
          type: "string"
        }
      }
    }
  },

  dependencies: {
    start: {
      properties: {
        end: {
          type: "object",
          properties: {
            time: {
              type: "string"
            }
          }
        }
      }
    }
  }
};

Essentially, I want a way for the dependency to depend not on the start property, but on the start.time property.

I've looked at this issue and the answer states that the schema cannot look "up" the tree, though I am not fully certain what "up" and "down" mean in this context.

The way I see it, if the dependency can depend on start, and time is a property within start, then time is "down" the tree, not "up" (?)


Solution

  • The dependencies keyword exists to simplify the schema for a specific use case. It sacrifices some flexibility and expressiveness for more simple syntax. Although your use case is very similar, it falls outside of what dependencies can do. The good news is that there's a way to do it.

    This,

    {
      "dependencies": {
        "some-propery-name": { ... some-schema ... }
      }
    }
    

    Is equivalent to,

    {
      "if": { "required": ["some-property-name"] },
      "then": { ... some-schema ... }
    }
    

    You can extrapolate from there to describe your use case.

    {
      "if": {
        "properties": {
          "start": { "required": ["time"] }
        },
        "required": ["start"]
      },
      "then": { ... some-schema ... }
    }