jsonschemaajv

Ajv — Use actual data in a schema


    field_name: {
      type: "object",
      properties: {
        min: { type: "number", minimum: 0, maximum: 600 },
        max: { type: "number", minimum: 0, maximum: 600 },
      },
      required: ["min", "max"],
      additionalProperties: false,
    },

I am using ajv to validate my objects in node.

For the object above, how do I further specify that max must always be greater than min?


Solution

  • You can actually use the data provided for one property in the schema of another but you need to enable $data as an option when creating your Ajv instance:

    note: $data is a JSON Pointer

    const ajv = new Ajv({$data: true});
    
    const validate = ajv.compile({
      type: 'object',
      properties: {
        min: {
          type: 'number',
          minimum: 0,
          exclusiveMaximum: 600
          // i.e. min >= 0 and min < 600
        },
        max: {
          type: 'number',
          exclusiveMinimum: {$data: "1/min"},
          maximum: 600
          // i.e. max > min and max <= 600
        }
      }
    });
    
    
    const test = (obj) => {
      const res = validate(obj);
      console.log(`{min: ${obj.min}, max: ${obj.max}} -> ${res}`);
      if (!res) console.log(validate.errors);
      return res;
    }
    
    test({min:   0, max: 500}); // true
    test({min: 500, max:   0}); // false
    test({min: 200, max: 200}); // false
    test({min: 599, max: 600}); // true
    test({min: 600, max: 600}); // false
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ajv/8.11.2/ajv7.bundle.js" integrity="sha512-gopWbU/o40XPlW4g/zJHfBUj1z9LKAWK6ZBFH5xiJHDDRRm8cXBo5UMLYTG5G42Pce8pBaWVNozLmvulanI3uQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script>
    const {ajv7: Ajv} = window;
    </script>