Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Errors for custom keywords / Sequence of initialization #32

Open
tjwoon opened this issue Jun 8, 2019 · 1 comment
Open

Errors for custom keywords / Sequence of initialization #32

tjwoon opened this issue Jun 8, 2019 · 1 comment

Comments

@tjwoon
Copy link

tjwoon commented Jun 8, 2019

Hello,

First of all, thank you for this library, and also for the main ajv library! :) I would just like to post this in order to save other people a few hours.

I discovered yesterday that it is important to add your keywords to your ajv instance before adding this ajv-errors plugin. Otherwise, customized error messages for your custom keywords will not appear, as your validators have not run by the time this plugin goes looking for custom error messages.

Example - if you init this plugin before adding your keywords:

const ajv = require('ajv')
const instance = new ajv({
  allErrors: true,
  jsonPointers: true
})

require('ajv-errors')(instance)

instance.addKeyword('testError', {
   validate: () => false
})

const validator = instance.compile({
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "https://workflow.rlscplatform.net/PPB_ASSAY",
  "type": "object",
  "properties": {
    "test": {
      "type": "string",
      "testError": true,
      "errorMessage": {
        "testError": "This is my custom error message"
      }
    }
  }
})

validator({
  test: "test"
})

console.log(validator.errors)

Outputs this:

[ { keyword: 'testError',
    dataPath: '/test',
    schemaPath: '#/properties/test/testError',
    params: { keyword: 'testError' },
    message: 'should pass "testError" keyword validation' } ]

But if you just put ajv-errors after your addKeyword:

instance.addKeyword('testError', {
   validate: () => false
})

require('ajv-errors')(instance)

The output becomes:

[ { keyword: 'errorMessage',
    dataPath: '/test',
    schemaPath: '#/properties/test/errorMessage',
    params: { errors: [Array] },
    message: 'This is my custom error message' } ]

Regards,
TJ

@epoberezkin
Copy link
Member

Worth adding to docs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants