josdejong / svelte-jsoneditor

A web-based tool to view, edit, format, repair, query, transform, and validate JSON
https://jsoneditoronline.org
Other
820 stars 108 forks source link

CreateAjvValidator : Unable to define additional formats #216

Closed Quentin-Mestre closed 1 year ago

Quentin-Mestre commented 1 year ago

First thing first, I really love your JSON editor !!!

I am facing a blocking issue : I am unable to define additionnal format validation (see Ajv documentation)using createAjvValidator function.

I am working with the Vue example you provide in the README, here is a sample of my code:

import { createAjvValidator } from "vanilla-jsoneditor";
...
const schema = {
  $schema: "http://json-schema.org/draft-07/schema",
  $id: "https://example.com/foo_bar_baz.schema.json",
  title: "A schema",
  description: "A schema description",
  type: "object",
  properties: {
    DATE_RANGES: {
      description: "List of date ranges",
      type: "array",
      items: {
        type: "array",
        items: {
          type: "string",
          format: "date-time",
        },
        minItems: 2,
        maxItems: 2,
      },
    },
  },
};

validator = createAjvValidator({
  schema,
  ajvOptions: { formats: ["date-time"] },
});
...

But on the validator construction, I get the following error in the browser console: Error: unknown format "date-time" ignored in schema at path "#/properties/DATE_RANGES/items/items"

I get the same error by using your https://jsoneditoronline.org/ with the same schema (in JSON):

{
  "$schema": "http://json-schema.org/draft-07/schema",
  "$id": "https://example.com/foo_bar_baz.schema.json",
  "title": "A schema",
  "description": "A schema description",
  "type": "object",
  "properties": {
    "DATE_RANGES": {
      "description": "List of date ranges",
      "type": "array",
      "items": {
        "type": "array",
        "items": {
          "type": "string",
          "format": "date-time"
        },
        "minItems": 2,
        "maxItems": 2
      }
    }
  }
}

My guess is that there is a missing addFormats call in createAjvValidator on format addition in ajvOptions.

josdejong commented 1 year ago

Thanks for your feedback. Have you tried adding formats like documented here: https://ajv.js.org/guide/formats.html ?

Something like the following should work (not tested):

import { createAjvValidator } from "vanilla-jsoneditor"
import addFormats from "ajv-formats"

const schema = ...

const validator = createAjvValidator({
  schema,
  onCreateAjv: (ajv) => {
    addFormats(ajv)
  }
})
josdejong commented 1 year ago

I'll see if I can add ajv-formats to https://jsoneditoronline.org (if it's not too large)

Quentin-Mestre commented 1 year ago

Hi again ! The first solution worked for me, thanks a lot ! :tada:

josdejong commented 1 year ago

👍