AJV Schema Validation DD/MM/YYYY Format in Typescript

  Kiến thức lập trình

I have the following schema and need to use a custom validation to check whether a string is in format DD/MM/YYYY. I’m using date-fns to validate the date. Typescript linting does not complain, but if I run the code, I have the following error:

Error: unknown format "ddmmyyyy" ignored in schema at path "#/properties/runDate"

Data input example:

{ runDate: "01/11/2023" }

Does anyone know what I’m doing wrong?

    import Ajv from 'ajv';
    import { parse, isValid } from "date-fns";

    const ajv = new Ajv();

    ajv.addFormat("ddmmyyyy", {
        validate: (date: string) => {
            const parsedDate = parse(date, 'dd/MM/yyyy', new Date());
            return isValid(parsedDate);
        },
        type: 'string',
    });

    const schema = {
    type: "object",
    properties: {
        runDate: {
            type: "string",
            format: "ddmmyyyy",
        }
    },
    required: ["runDate"],
    additionalProperties: false
};

LEAVE A COMMENT