JSON Schema validation for Human π¨βπ€
Main goal of this library is to provide relevant error messages like the following:
- Only targets current Node LTS releases.
- AJV 8 support.
- Default errors stack the error message at the top of the location instead of the bottom.
- This helps eliminate long blocks of
^^^^^^
pointers.
- This helps eliminate long blocks of
- Addition of a
colorize
option for disabling colorization informat: cli
output. - Up-to-date dependencies.
$ npm i @readme/better-ajv-errors
$ yarn add @readme/better-ajv-errors
$ pnpm add @readme/better-ajv-errors
Also make sure that you installed ajv package to validate data against JSON schemas.
First, you need to validate your payload with ajv
. If it's invalid then you can pass validate.errors
object into better-ajv-errors
.
import Ajv from 'ajv';
import betterAjvErrors from '@readme/better-ajv-errors';
// const Ajv = require('ajv');
// const betterAjvErrors = require('@readme/better-ajv-errors');
// You need to pass `{ jsonPointers: true }` for older versions of ajv
const ajv = new Ajv();
// Load schema and data
const schema = ...;
const data = ...;
const validate = ajv.compile(schema);
const valid = validate(data);
if (!valid) {
const output = betterAjvErrors(schema, data, validate.errors);
console.log(output);
}
Returns formatted validation error to print in console
. See options.format
for further details.
Type: Object
The JSON Schema you used for validation with ajv
Type: Object
The JSON payload you validate against using ajv
Type: Array
Array of ajv validation errors
Type: Object
Type: boolean
Default: true
When disabled, if you are outputting cli
formatting it will be without colorized or styled content.
Type: string
Default: cli
Values: cli
js
Use default cli
output format if you want to print beautiful validation errors like following:
Or, use js
if you are planning to use this with some API. Your output will look like following:
[
{
start: { line: 6, column: 15, offset: 70 },
end: { line: 6, column: 26, offset: 81 },
error: '/content/0/type should be equal to one of the allowed values: panel, paragraph, ...',
suggestion: 'Did you mean paragraph?',
},
];
Type: number
null
Default: null
If you have an unindented JSON payload and you want the error output indented.
This option have no effect when using the json
option.
Type: string
null
Default: null
Raw JSON payload used when formatting codeframe. Gives accurate line and column listings.