Skip to content

Custom JSON Schema Validation Keywords (AJV) ​

Using ajv as plugin, the Schema Validation Keywords (AJV) functionalities will be enabled and can be extended too.

See the ajv documentation: Defining Custom Keywords for a deeper explaination

Below we see how to implement it in mobx-formkit:

Define a keywords object with the custom keyword ​

javascript

const keywords = {
  /**
    Define a `range` keyword
  */
  range: {
    type: 'number',
    compile: (sch, parentSchema) => {
      const min = sch[0];
      const max = sch[1];

      return parentSchema.exclusiveRange === true
              ? (data) => (data > min && data < max)
              : (data) => (data >= min && data <= max);
    },
  },
};

Define a JSON schema using the new keyword ​

javascript
var $schema = {
  type: 'object',
  properties: {
    fieldname: {
      "range": [2, 4],
      "exclusiveRange": true,
    },
  },
};

Implement the extend callback for the plugins object ​

The extend function takes in input an object with the following props:

  • the form instance
  • the validator instance
javascript
import ajv from 'mobx-formkit/lib/validators/AJV';
import Ajv from 'ajv';

const plugins = {
  ajv: ajv({
    package: Ajv,
    schema: $schema,
    options: { ... }, // ajv options
    extend: ({ validator, form }) => {
      // here we can access the `ajv` instance (validator) and we can
      // add the keywords of our object using the `addKeyword()` method.
      Object.keys(keywords).forEach((key) =>
        validator.addKeyword(key, keywords[key]));
    };
  }),
};
VERSION < 1.37

No need to import the plugin function:

javascript
import Ajv from 'ajv';

const plugins = {
  ajv: {
    package: Ajv,
    extend: () => { ... },
  },
};

and the schema goes to the form initialization:

javascript
new Form({ ..., schema }, { plugins });

See here more info about epoberezkin/ajv options.

Released under the MIT License.