Custom error messages in JSON Schemas for Ajv validator
Installations
npm install ajv-errors
Score
98
Supply Chain
100
Quality
75.6
Maintenance
100
Vulnerability
100
License
Developer
Developer Guide
Module System
CommonJS
Min. Node Version
Typescript Support
Yes
Node Version
14.16.0
NPM Version
6.14.11
Statistics
285 Stars
99 Commits
18 Forks
6 Watching
9 Branches
5 Contributors
Updated on 16 Nov 2024
Bundle Size
6.28 kB
Minified
2.22 kB
Minified + Gzipped
Languages
TypeScript (97.27%)
JavaScript (2.73%)
Total Downloads
Cumulative downloads
Total Downloads
2,449,321,278
Last day
-7.6%
1,318,886
Compared to previous day
Last week
2%
7,120,855
Compared to previous week
Last month
19.5%
28,843,417
Compared to previous month
Last year
-27.5%
326,999,814
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
ajv-errors
Custom error messages in JSON-Schema for Ajv validator
Please note
ajv-errors v3 supports ajv v8.
If you are using ajv v6, you should use ajv-errors v1
Contents
Install
npm install ajv-errors
Usage
Add the keyword errorMessages
to Ajv instance:
1const Ajv = require("ajv").default 2const ajv = new Ajv({allErrors: true}) 3// Ajv option allErrors is required 4require("ajv-errors")(ajv /*, {singleError: true} */)
See Options below.
Single message
Replace all errors in the current schema and subschemas with a single message:
1const schema = { 2 type: "object", 3 required: ["foo"], 4 properties: { 5 foo: {type: "integer"}, 6 }, 7 additionalProperties: false, 8 errorMessage: "should be an object with an integer property foo only", 9} 10 11const validate = ajv.compile(schema) 12console.log(validate({foo: "a", bar: 2})) // false 13console.log(validate.errors) // processed errors
Processed errors:
1[ 2 { 3 keyword: "errorMessage", 4 message: "should be an object with an integer property foo only", 5 // ... 6 params: { 7 errors: [ 8 {keyword: "additionalProperties", instancePath: "" /* , ... */}, 9 {keyword: "type", instancePath: ".foo" /* , ... */}, 10 ], 11 }, 12 }, 13]
Messages for keywords
Replace errors for certain keywords in the current schema only:
1const schema = { 2 type: "object", 3 required: ["foo"], 4 properties: { 5 foo: {type: "integer"}, 6 }, 7 additionalProperties: false, 8 errorMessage: { 9 type: "should be an object", // will not replace internal "type" error for the property "foo" 10 required: "should have property foo", 11 additionalProperties: "should not have properties other than foo", 12 }, 13} 14 15const validate = ajv.compile(schema) 16console.log(validate({foo: "a", bar: 2})) // false 17console.log(validate.errors) // processed errors
Processed errors:
1[ 2 { 3 // original error 4 keyword: type, 5 instancePath: "/foo", 6 // ... 7 message: "should be integer", 8 }, 9 { 10 // generated error 11 keyword: "errorMessage", 12 message: "should not have properties other than foo", 13 // ... 14 params: { 15 errors: [{keyword: "additionalProperties" /* , ... */}], 16 }, 17 }, 18]
For keywords "required" and "dependencies" it is possible to specify different messages for different properties:
1const schema = { 2 type: "object", 3 required: ["foo", "bar"], 4 properties: { 5 foo: {type: "integer"}, 6 bar: {type: "string"}, 7 }, 8 errorMessage: { 9 type: "should be an object", // will not replace internal "type" error for the property "foo" 10 required: { 11 foo: 'should have an integer property "foo"', 12 bar: 'should have a string property "bar"', 13 }, 14 }, 15}
Messages for properties and items
Replace errors for properties / items (and deeper), regardless where in schema they were created:
1const schema = { 2 type: "object", 3 required: ["foo", "bar"], 4 allOf: [ 5 { 6 properties: { 7 foo: {type: "integer", minimum: 2}, 8 bar: {type: "string", minLength: 2}, 9 }, 10 additionalProperties: false, 11 }, 12 ], 13 errorMessage: { 14 properties: { 15 foo: "data.foo should be integer >= 2", 16 bar: "data.bar should be string with length >= 2", 17 }, 18 }, 19} 20 21const validate = ajv.compile(schema) 22console.log(validate({foo: 1, bar: "a"})) // false 23console.log(validate.errors) // processed errors
Processed errors:
1[ 2 { 3 keyword: "errorMessage", 4 message: "data.foo should be integer >= 2", 5 instancePath: "/foo", 6 // ... 7 params: { 8 errors: [{keyword: "minimum" /* , ... */}], 9 }, 10 }, 11 { 12 keyword: "errorMessage", 13 message: "data.bar should be string with length >= 2", 14 instancePath: "/bar", 15 // ... 16 params: { 17 errors: [{keyword: "minLength" /* , ... */}], 18 }, 19 }, 20]
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 using _
property:
1const schema = { 2 type: "object", 3 required: ["foo", "bar"], 4 allOf: [ 5 { 6 properties: { 7 foo: {type: "integer", minimum: 2}, 8 bar: {type: "string", minLength: 2}, 9 }, 10 additionalProperties: false, 11 }, 12 ], 13 errorMessage: { 14 type: "data should be an object", 15 properties: { 16 foo: "data.foo should be integer >= 2", 17 bar: "data.bar should be string with length >= 2", 18 }, 19 _: 'data should have properties "foo" and "bar" only', 20 }, 21} 22 23const validate = ajv.compile(schema) 24console.log(validate({})) // false 25console.log(validate.errors) // processed errors
Processed errors:
1[ 2 { 3 keyword: "errorMessage", 4 message: 'data should be an object with properties "foo" and "bar" only', 5 instancePath: "", 6 // ... 7 params: { 8 errors: [{keyword: "required" /* , ... */}, {keyword: "required" /* , ... */}], 9 }, 10 }, 11]
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:
1const schema = { 2 type: "object", 3 properties: { 4 size: { 5 type: "number", 6 minimum: 4, 7 }, 8 }, 9 errorMessage: { 10 properties: { 11 size: "size should be a number bigger or equal to 4, current value is ${/size}", 12 }, 13 }, 14}
Using property names in error messages
Property names can be used in error messages with the relative JSON-pointer (e.g. 0#
).
Example:
1const schema = { 2 type: "object", 3 properties: { 4 size: { 5 type: "number", 6 }, 7 }, 8 additionalProperties: { 9 not: true, 10 errorMessage: “extra property is ${0#}” 11 } 12}
Options
Defaults:
1{ 2 keepErrors: false, 3 singleError: false, 4}
- 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 byerrorMessage
keyword it will have propertyemUsed: 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 instancePaths). Multiple error messages are concatenated. Option values:false
(default): create multiple errors, one for each messagetrue
: create single error, messages are concatenated using"; "
- non-empty string: this string is used as a separator to concatenate messages
Supporters
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
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
Found 2/18 approved changesets -- score normalized to 1
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/build.yml:1
- Warn: no topLevel permission defined: .github/workflows/publish.yml:1
- Info: no jobLevel write permissions found
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/build.yml:18: update your workflow using https://app.stepsecurity.io/secureworkflow/ajv-validator/ajv-errors/build.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/build.yml:20: update your workflow using https://app.stepsecurity.io/secureworkflow/ajv-validator/ajv-errors/build.yml/master?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/build.yml:26: update your workflow using https://app.stepsecurity.io/secureworkflow/ajv-validator/ajv-errors/build.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/publish.yml:11: update your workflow using https://app.stepsecurity.io/secureworkflow/ajv-validator/ajv-errors/publish.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/publish.yml:12: update your workflow using https://app.stepsecurity.io/secureworkflow/ajv-validator/ajv-errors/publish.yml/master?enable=pin
- Warn: npmCommand not pinned by hash: .github/workflows/build.yml:24
- Warn: npmCommand not pinned by hash: .github/workflows/publish.yml:17
- Info: 0 out of 4 GitHub-owned GitHubAction dependencies pinned
- Info: 0 out of 1 third-party GitHubAction dependencies pinned
- Info: 0 out of 2 npmCommand dependencies pinned
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'master'
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 15 are checked with a SAST tool
Score
3.5
/10
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More