Search code examples
javascriptnode.jsjsonjsonschemaajv

how to validate object schema where the fields depend on each other using ajv?


I am using ajv node package to validate my schemas. Supposed that a field holds an object type.

The object can have 3 properties: "A", "B", and "C".

How do I specify that at least one of these properties must be defined and no other properties are allowed?


Solution

  • Depending on if you want to disallow all other properties or just the specific other ones (if "A" is present, "B" and "C" are forbidden but "foo" is still OK) you can either use oneOf with the additionalProperties: false property or use not to disallow specific properties. Example for both:

    schmema:

    {
      "anyOf": [
        {
          "properties": {"A": {}},
          "required": ["A"],
          "additionalProperties": false
        },
        {
          "properties": {
            "B": {},
            "A": { "not": {} },
            "C": { "not": {} }
          },
          "required": ["B"],
        }
      ]
    }
    

    Note: The pattern "not": {} is always false so no value for the corresponding property can ever fulfill it.

    This example uses additionalProperties: false for "A" so it matches

    {
          "A": 3
    }
    

    but neither

    {
        "A": 3,
        "B": 5
    }
    

    nor

    {
        "A": 3,
        "foo": 5
    }
    

    On the other hand, the example uses not for the "B" case so it matches

    {
          "B": 3
    }
    

    and

    {
        "B": 3,
        "foo": 5
    }
    

    but not

    {
        "A": 3,
        "C": 5
    }