Security News
Supply Chain Attack Detected in Solana's web3.js Library
A supply chain attack has been detected in versions 1.95.6 and 1.95.7 of the popular @solana/web3.js library.
ajv-errors
Advanced tools
The ajv-errors package allows you to customize error messages in JSON Schema validation using the Ajv validator. It provides a way to enhance the default error messages that Ajv produces, making them more informative and user-friendly. This can be particularly useful in applications where precise and clear validation errors are necessary, such as form validation in web applications.
Custom error messages for specific validation keywords
This feature allows you to specify custom error messages for specific validation keywords, such as 'required', 'type', etc. In the provided code sample, a custom error message is defined for when the 'name' field is missing.
{ "type": "object", "properties": { "name": { "type": "string" } }, "required": ["name"], "errorMessage": { "required": { "name": "Name is required." } } }
Conditional error messages
This feature enables conditional error messages based on the validation outcome. In the example, a custom error message is set for the 'passwordConfirm' field to ensure it matches the 'password' field.
{ "type": "object", "properties": { "password": { "type": "string" }, "passwordConfirm": { "type": "string", "const": { "$data": "1/password" } } }, "errorMessage": { "properties": { "passwordConfirm": "Passwords must match." } } }
Top-level error messages
Allows setting a top-level error message for the entire schema. This is useful for providing a general error message instead of or in addition to specific field errors. The example sets a general error message regarding the 'age' field.
{ "type": "object", "properties": { "age": { "type": "number" } }, "required": ["age"], "errorMessage": "An age is required and must be a number." }
Joi is a powerful schema description language and data validator for JavaScript. Unlike ajv-errors, which works specifically with JSON Schema and Ajv, Joi provides its own schema definition syntax and validation mechanism. It allows for custom error messages, but its approach and syntax differ significantly from ajv-errors.
Yup is another JavaScript schema builder for value parsing and validation. Similar to ajv-errors, Yup allows for custom error messages and has a fluent interface for defining schemas and validations. However, Yup uses its own schema definition and validation system, offering a different API and feature set compared to 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
npm install ajv-errors
Add the keyword errorMessages
to Ajv instance:
const Ajv = require("ajv").default
const ajv = new Ajv({allErrors: true})
// Ajv option allErrors is required
require("ajv-errors")(ajv /*, {singleError: true} */)
See Options below.
Replace all errors in the current schema and subschemas with a single message:
const schema = {
type: "object",
required: ["foo"],
properties: {
foo: {type: "integer"},
},
additionalProperties: false,
errorMessage: "should be an object with an integer property foo only",
}
const 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", instancePath: "" /* , ... */},
{keyword: "type", instancePath: ".foo" /* , ... */},
],
},
},
]
Replace errors for certain keywords in the current schema only:
const 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",
},
}
const validate = ajv.compile(schema)
console.log(validate({foo: "a", bar: 2})) // false
console.log(validate.errors) // processed errors
Processed errors:
[
{
// original error
keyword: type,
instancePath: "/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:
const 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"',
},
},
}
Replace errors for properties / items (and deeper), regardless where in schema they were created:
const 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",
},
},
}
const 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",
instancePath: "/foo",
// ...
params: {
errors: [{keyword: "minimum" /* , ... */}],
},
},
{
keyword: "errorMessage",
message: "data.bar should be string with length >= 2",
instancePath: "/bar",
// ...
params: {
errors: [{keyword: "minLength" /* , ... */}],
},
},
]
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:
const 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',
},
}
const 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',
instancePath: "",
// ...
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.
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:
false
and "false"
, etc.Example:
const schema = {
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}",
},
},
}
Property names can be used in error messages with the relative JSON-pointer (e.g. 0#
).
Example:
const schema = {
type: "object",
properties: {
size: {
type: "number",
},
},
additionalProperties: {
not: true,
errorMessage: “extra property is ${0#}”
}
}
Defaults:
{
keepErrors: false,
singleError: false,
}
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
.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 "; "
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.
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.
FAQs
Custom error messages in JSON Schemas for Ajv validator
We found that ajv-errors demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
A supply chain attack has been detected in versions 1.95.6 and 1.95.7 of the popular @solana/web3.js library.
Research
Security News
A malicious npm package targets Solana developers, rerouting funds in 2% of transactions to a hardcoded address.
Security News
Research
Socket researchers have discovered malicious npm packages targeting crypto developers, stealing credentials and wallet data using spyware delivered through typosquats of popular cryptographic libraries.