ajv-validator / ajv-errors

Custom error messages in JSON Schemas for Ajv validator
https://ajv.js.org
MIT License
282 stars 18 forks source link

errorMessage not being set on array of objects? #146

Closed Breadkenty closed 1 year ago

Breadkenty commented 1 year ago

Hi,

I have the following JSON that I am trying to validate:

[
    {
        "id": "1",
        "externalId": "four"
    },
    {
        "id": "2a",
        "externalId": "three"
    },
    {
        "id": "3b",
        "externalId": "two"
    },
    {
        "id": "4",
        "externalId": "one"
    }
]

I want the validator to throw an error for the id property on the values with 2a and 3b . This is my model and the schema I am using:

interface CompanyIdPair {
    id: string;
    externalId: string;
}

const companyIdPairSchema: JSONSchemaType<CompanyIdPair> = {
    $id: 'CompanyIdPair',
    type: 'object',
    properties: {
        id: { type: 'string', pattern: '^\\d+$' },
        externalId: { type: 'string' },
    },
    required: ['id', 'externalId'],
    additionalProperties: false,
    errorMessage: {
        properties: {
            id: " Invalid 'id' at '${/id}', must be a numeric",
        },
    },
};

const companyIdPairsSchema: JSONSchemaType<CompanyIdPair[]> = {
    $id: 'CompanyIdPairs',
    type: 'array',
    items: companyIdPairSchema,
};

When I try to validate the schema and display the errors received with the following code

import Ajv, { JSONSchemaType } from 'ajv';
import ajvErrors from 'ajv-errors';

const ajv = new Ajv({ allErrors: true });
ajvErrors(ajv);

const companyIdPairs = JSON.parse(event.body) as CompanyIdPair[];

const validate = ajv.compile(companyIdPairsSchema);
validate(companyIdPairs);

console.log(validate.errors?.map(error => error.message));

I keep getting the errors:

[ 'must match pattern "^\\d+$"', 'must match pattern "^\\d+$"' ]

Instead of:

['Invalid 'id' at '"2a"', must be a numeric', 'Invalid 'id' at '"3b"', must be a numeric']

Any solution to this would be fantastic, thanks!

Breadkenty commented 1 year ago
{
    $id: 'CompanyIdPair',
    type: 'object',
    properties: {
        id: {
            type: 'string',
            pattern: '^\\d+$',
            errorMessage: { pattern: "\${1/id} is an invalid \${0#}, must be a numeric string."  },
        },
        externalId: { type: 'string', errorMessage: {
            type: "\${1/id} is an invalid \${0#}, must be a string."
        } },
    },
    required: ['id', 'externalId'],
    additionalProperties: false,
};

This fixed it for me