npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

ajv-errors-with-data

v1.0.1

Published

Custom error messages in JSON-Schema for Ajv validator

Downloads

531

Readme

ajv-errors

Custom error messages in JSON-Schema for Ajv validator

Build Status npm version Coverage Status Gitter

Contents

Install

npm install ajv-errors

Usage

Add the keyword errorMessages to Ajv instance:

var Ajv = require('ajv');
var ajv = new Ajv({allErrors: true, jsonPointers: true});
// Ajv options allErrors and jsonPointers are required
require('ajv-errors')(ajv /*, {singleError: true} */);

See Options below.

Single message

Replace all errors in the current schema and subschemas with a single message:

var schema = {
  type: 'object',
  required: ['foo'],
  properties: {
    foo: { type: 'integer' }
  },
  additionalProperties: false,
  errorMessage: 'should be an object with an integer property foo only'
};

var validate = ajv.compile(schema);
console.log(validate({foo: 'a', bar: 2})); // false
console.log(validate.errors); // processed errors

Processed errors:

[
  {
    keyword: 'errorMessage',
    message: 'should be an object with an integer property foo only',
    // ...
    params: {
      errors: [
        { keyword: 'additionalProperties', dataPath: '' /* , ... */ },
        { keyword: 'type', dataPath: '.foo' /* , ... */ }
      ]
    }
  }
]

Messages for keywords

Replace errors for certain keywords in the current schema only:

var schema = {
  type: 'object',
  required: ['foo'],
  properties: {
    foo: { type: 'integer' }
  },
  additionalProperties: false,
  errorMessage: {
    type: 'should be an object', // will not replace internal "type" error for the property "foo"
    required: 'should have property foo',
    additionalProperties: 'should not have properties other than foo'
  }
};

var validate = ajv.compile(schema);
console.log(validate({foo: 'a', bar: 2})); // false
console.log(validate.errors); // processed errors

Processed errors:

[
  {
    // original error
    keyword: type,
    dataPath: '/foo',
    // ...
    message: 'should be integer'
  },
  {
    // generated error
    keyword: 'errorMessage',
    message: 'should not have properties other than foo',
    // ...
    params: {
      errors: [
        { keyword: 'additionalProperties' /* , ... */ }
      ]
    },
  }
]

For keywords "required" and "dependencies" it is possible to specify different messages for different properties:

var schema = {
  type: 'object',
  required: ['foo', 'bar'],
  properties: {
    foo: { type: 'integer' },
    bar: { type: 'string' }
  },
  errorMessage: {
    type: 'should be an object', // will not replace internal "type" error for the property "foo"
    required: {
      foo: 'should have an integer property "foo"',
      bar: 'should have a string property "bar"'
    }
  }
};

Messages for properties and items

Replace errors for properties / items (and deeper), regardless where in schema they were created:

var schema = {
  type: 'object',
  required: ['foo', 'bar'],
  allOf: [{
    properties: {
      foo: { type: 'integer', minimum: 2 },
      bar: { type: 'string', minLength: 2 }
    },
    additionalProperties: false
  }],
  errorMessage: {
    properties: {
      foo: 'data.foo should be integer >= 2',
      bar: 'data.bar should be string with length >= 2'
    }
  }
};

var validate = ajv.compile(schema);
console.log(validate({foo: 1, bar: 'a'})); // false
console.log(validate.errors); // processed errors

Processed errors:

[
  {
    keyword: 'errorMessage',
    message: 'data.foo should be integer >= 2',
    dataPath: '/foo',
    // ...
    params: {
      errors: [
        { keyword: 'minimum' /* , ... */ }
      ]
    },
  },
  {
    keyword: 'errorMessage',
    message: 'data.bar should be string with length >= 2',
    dataPath: '/bar',
    // ...
    params: {
      errors: [
        { keyword: 'minLength' /* , ... */ }
      ]
    },
  }
]

Default message

When the value of keyword errorMessage is an object you can specify a message that will be used if any error appears that is not specified by keywords/properties/items:

var schema = {
  type: 'object',
  required: ['foo', 'bar'],
  allOf: [{
    properties: {
      foo: { type: 'integer', minimum: 2 },
      bar: { type: 'string', minLength: 2 }
    },
    additionalProperties: false
  }],
  errorMessage: {
    type: 'data should be an object',
    properties: {
      foo: 'data.foo should be integer >= 2',
      bar: 'data.bar should be string with length >= 2'
    },
    _: 'data should have properties "foo" and "bar" only'
  }
};

var validate = ajv.compile(schema);
console.log(validate({})); // false
console.log(validate.errors); // processed errors

Processed errors:

[
  {
    keyword: 'errorMessage',
    message: 'data should be an object with properties "foo" and "bar" only',
    dataPath: '',
    // ...
    params: {
      errors: [
        { keyword: 'required' /* , ... */ },
        { keyword: 'required' /* , ... */ }
      ]
    },
  }
]

The message in property _ of errorMessage replaces the same errors that would have been replaced if errorMessage were a string.

Templates

Custom error messages used in errorMessage keyword can be templates using JSON-pointers or relative JSON-pointers to data being validated, in which case the value will be interpolated. Also see examples of relative JSON-pointers.

The syntax to interpolate a value is ${<pointer>}.

The values used in messages will be JSON-stringified:

  • to differentiate between false and "false", etc.
  • to support structured values.

Example:

{
  "type": "object",
  "properties": {
    "size": {
      "type": "number",
      "minimum": 4
    }
  },
  "errorMessage": {
    "properties": {
      "size": "size should be a number bigger or equal to 4, current value is ${/size}"
    }
  }
}

Options

Defaults:

{
  keepErrors: false,
  singleError: false
}
  • keepErrors: keep original errors. Default is to remove matched errors (they will still be available in params.errors property of generated error). If an error was matched and included in the error generated by errorMessage keyword it will have property emUsed: true.
  • singleError: create one error for all keywords used in errorMessage keyword (error messages defined for properties and items are not merged because they have different dataPaths). Multiple error messages are concatenated. Option values:
    • false (default): create multiple errors, one for each message
    • true: create single error, messages are concatenated using "; "
    • non-empty string: this string is used as a separator to concatenate messages

Supporters

Roger Kepler

Enterprise support

ajv-errors package is a part of Tidelift enterprise subscription - it provides a centralised commercial support to open-source software users, in addition to the support provided by software maintainers.

Security contact

To report a security vulnerability, please use the Tidelift security contact. Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerability via GitHub issues.

License

MIT