hyperjump-io/json-schema

Adding formats

silverwind opened this issue · 2 comments

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));

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.

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.