JSPM

  • Created
  • Published
  • Downloads 729267
  • Score
    100M100P100Q191196F
  • License MIT

JSON Schema validation for Human

Package Exports

  • better-ajv-errors
  • better-ajv-errors/lib/modern

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (better-ajv-errors) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

better-ajv-errors

JSON Schema validation for Human

npm CircleCI Codecov bitHound

Main goal of this library is to provide relevant error messages like the following:

Enum Validation Error

You can also use it in "return" mode when library returns structured errors.

Installation

$ yarn add better-ajv-errors
$ # Or
$ npm i better-ajv-errors

Also make sure that you installed ajv package to validate data against JSON schemas.

Usage

You need to validate data first with ajv. Then you can pass validate.errors object into better-ajv-errors.

import Ajv from 'ajv';
// const Ajv = require('ajv');
import betterAjvErrors from 'better-ajv-errors';
// const betterAjvErrors = require('better-ajv-errors');

// You need to pass `jsonPointers: true`
const ajv = new Ajv({ jsonPointers: true });

// Load schema and data
const schema = ...;
const data = ...;

const validate = ajv.compile(schema);
const valid = validate(data);
// ...validate data first
const print = betterAjvErrors({ schema, mode: 'print', indent: 2 });

if (!valid) {
  print(data, validate.errors);
}

"Return" mode

// ...validate data first
const getHumanErrors = betterAjvErrors({ schema, mode: 'return', indent: 2 });

if (!valid) {
  const errors = getHumanErrors(data, validate.errors);

  /*
  errors is array: [
    {
      "error": "You're using invalid field FOO",
      "line": 14,
      "column": 75,
      "suggestion": "Maybe you meant BAR?"
    }
  ]
  */
}