You can override default JSON Schema error messages by adding the x-error keyword to your schema. x-error takes precedence over I18n translations.
It supports several modes:
- String: A single string used for the schema and all its keywords.
- Hash: Allows keyword-specific overrides.
- Use the specific keyword name (e.g.,
'type') for targeted messages. - Use
'^' to define a fallback error for the schema itself. - Use
'*' to define a fallback error for the schema and all its keywords.
Variable Interpolation
Inside an x-error string or template, you can use the following variables to inject context into the error message:
%{instance}: The data being validated.%{instanceLocation}: The JSON pointer to the data.%{formattedInstanceLocation}: The JSON pointer formatted as a code literal.%{keywordValue}: The value of the keyword that failed.%{keywordLocation}: The JSON pointer to the keyword in the schema.%{absoluteKeywordLocation}: The absolute URI to the keyword in the schema.%{details}: A hash of additional error details.%{details__<key>}: Accesses a specific key within the details hash (e.g., %{details__missing_keys}).
# keyword-specific errors
schemer = JSONSchemer.schema({
'type' => 'string',
'minLength' => 10,
'x-error' => {
'type' => 'custom error for `type` keyword',
'^' => 'custom error for schema',
'*' => 'fallback error for schema and all keywords'
}
})
# variable interpolation example
schemer = JSONSchemer.schema({
'properties' => {
'abc' => {
'type' => 'object',
'required' => ['xyz'],
'x-error' => "instance: %{instance}, location: %{instanceLocation}"
}
}
})