hyperjump-io / json-schema

JSON Schema Validation, Annotation, and Bundling. Supports Draft 04, 06, 07, 2019-09, 2020-12, OpenAPI 3.0, and OpenAPI 3.1
https://json-schema.hyperjump.io/
MIT License
221 stars 21 forks source link

Adding formats #36

Closed silverwind closed 1 year ago

silverwind commented 1 year ago

JSON schema defines a few built-in formats for the format keyword, but as far as I can tell, none work with this module. Would it be possible to add a addFormat function to define such formats, for example:

addFormat("email", str => emailRe.test(str));
jdesrosiers commented 1 year ago

This package doesn't support any format validation and I don't have plans to add support any time soon. Validation of the a value based on format has always been optional and in recent versions required to not validate by default if the implementation supports it.

However, you have the power to override the default implementation for the format keyword and replace it with your own version that does validate.

import { addKeyword } from "@hyperjump/json-schema/experimental";
import * as Schema from "@hyperjump/json-schema/schema/experimental";
import * as Instance from "@hyperjump/json-schema/instance/experimental";

addKeyword({
  id: "https://json-schema.org/keyword/format",
  compile: Schema.value,
  interpret: (format, instance) => {
    switch (format) {
      case "email":
        return emailRe.test(Instance.value(instance));
      default:
        return true;
   }
  }
});

Using the id https://json-schema.org/keyword/format will override the existing implementation that all of the dialects map the keyword format to.

silverwind commented 1 year ago

Thanks, I do understand a reasoning not wanting to maintain formats and there already packages that provide the most common ones like ajv-formats. That example seems good enough for me, and it looks extendable enough.

Maybe consider adding this example to the README. I think many people might need it.