AJV v8.17.1 has been working for validations in our project for a while, but we had never used it for an array type.
We recently added the "codes" array to this object:
{"name":"a","codes":["A01"]}
And now when the AJV "compile" method is hit, it is throwing this error:
strict mode: unknown keyword: \"elements\"
Here is the validation code (TS compliant in our VS Code project):
import { JTDSchemaType } from 'ajv/dist/core';
import Ajv from 'ajv';
type TempDetails = {
name: string;
codes: string[];
};
type JTDTempDetailsCreateRequestSchema = JTDSchemaType<TempDetails>;
const jtdTempDetailsCreateRequestSchema: JTDTempDetailsCreateRequestSchema = {
properties: {
name: { type: 'string' },
codes: { elements: { type: 'string' } },
},
};
const ajv = new Ajv();
const validate = ajv.compile<TempDetails>(jtdTempDetailsCreateRequestSchema);
if (!validate(untypedClass))
throw new BadRequest(`Invalid Request: ${JSON.stringify(validate.errors)}`);
It turns out that { elements: { type: 'string' } }
is correct per the docs: https://ajv.js.org/json-type-definition.html#elements-form
but an auto-import occurred that resulted in the wrong import path being used.
Incorrect import caused the issue: import Ajv from 'ajv';
Corrected import resolved the issue: import Ajv from 'ajv/dist/jtd';
The incorrect import led to the wrong AJV validation being used.
This caused confusion since the error only occurred for the array and not for the first line name: { type: 'string' }