Search code examples
javascriptajv

Ajv library: Accessing keys in the nested schema validation javascript


I'm working on the use case where I need to validate the schema using ajv lib of the provided data which can be nested.

Now the problem is, Schema could change based on the value of a particular variable, which is not in the scope where this check is to be done.

how do I achieve it through ajv.

I tried using if-else & data & const but no luck.


Solution

  • I've recently encountered similar use case with ajv validator. By looking at your issue I believe you need to access some other scope of the actual object passed for validation, In my case it was lying in the root of the object.

    So I used the validate function in ajv's User Defined Keyword section, which in turn is giving me the whole object from top level in the first index of arguments itself, that way I accessed my dependent key in validate function and used it in my ajv IF: condition, eg

    ajv.addKeyword({
      keyword: "isRegular",
      validate: (...test) =>  {
        const test1 = test[1]
        return test1.dependentKeyFromRootOfObject === "REGULAR"
      },
    })
    

    and used the then created keyword isRegular in the nested object's IF: condition like

      if: { isRegular: true },
      then: {
        properties: {
          rcType: { type: "string" },
          date: { type: "string" },
        },
        required: ["rcType", "date"],
        additionalProperties: false,
      },
      else: {
        properties: {
          rcType: { type: "string" },
        },
        required: ["rcType"],
        additionalProperties: false,
      },
    

    Hope this helps.