node.jsdatabase-designjsonschemajson-schema-validatorajv

Ajv - validate utc data with age requirement


I have a field that stores an integer donating date of birth in UTC time:

utc_millisecond: {
    type: "integer",
    minimum: -5361984000000, // 1800
    maximum: 2527290061000, // 2050
}

The problem with the above schema is that, the values are static while time always goes forward.

There is a requirement that the dob_milliseond value translates to an age that is greater than 18 and less than 100.

How do I further specify this above requirement?

EDITED:

I already have a function that converts utc milliseconds to age:

function utc_to_age(utc) {

}

So I just need to integrate this custom function into the ajv schema validator


Solution

  • I figured out a way:

      ajv_inst.addKeyword({
        keyword: "dob_utc_int",
        validate: (schema, data) => {
          if (!Number.isInteger(data)) {
            return false;
          }
          const age = utc_to_age(data);
          return schema.max_age >= age && schema.min_age <= age;
        },
        metaSchema: {
          // compilation error
          // schema to validate keyword value
          type: "object",
          properties: {
            min_age: {
              type: "integer",
              minimum: 18,
              maximum: 150,
            },
            max_age: {
              type: "integer",
              minimum: { $data: "1/min_age" },
              maximum: 150,
            },
          },
          required: ["min_age", "max_age"],
          additionalProperties: false,
        },
      });
    

    Now just need to have it print error messages.