@cfworker/json-schema

A JSON schema validator that will run on Cloudflare workers. Supports drafts 4, 7, and 2019-09.

Usage no npm install needed!

<script type="module">
  import cfworkerJsonSchema from 'https://cdn.skypack.dev/@cfworker/json-schema';
</script>

README

@cfworker/json-schema

A JSON schema validator that will run on Cloudflare workers. Supports drafts 4, 7, and 2019-09.

background

Why another JSON schema validator?

Cloudflare workers do not have APIs required by Ajv schema compilation (eval or new Function(code)). If possible use Ajv in a build step to precompile your schema. Otherwise use this library.

basic usage

import { Validator } from '@cfworker/json-schema';

const validator = new Validator({ type: 'number' });

const result = validator.validate(7);

specify meta schema draft

const validator = new Validator({ type: 'number' }, '4'); // draft-4

add schemas

const validator = new Validator({
  $id: 'https://foo.bar/baz',
  $ref: '/beep'
});

validator.addSchema({ $id: 'https://foo.bar/beep', type: 'boolean' });

include all errors

By default the validator stops processing after the first error. Set the shortCircuit parameter to false to emit all errors.

const shortCircuit = false;

const draft = '2019-09';

const schema = {
  type: 'object',
  required: ['name', 'email', 'number', 'bool'],
  properties: {
    name: { type: 'string' },
    email: { type: 'string', format: 'email' },
    number: { type: 'number' },
    bool: { type: 'boolean' }
  }
};

const validator = new Validator(schema, draft, shortCircuit);

const result = validator.validate({
  name: 'hello',
  email: 5, // invalid type
  number: 'Hello' // invalid type
  bool: 'false' // invalid type
});