How to customise error message for invalid input?
json, json-schema-validator, jsonschema
Solution
Custom error messages are not supported. However, there is some discussion going on to add a feature like this in the next version of JSON Schema.
Update 2021-01-26
JSON Schema never ended up supporting the customization of error messages in this way. The main problem with this is that appropriate error messaging is dependent on the audience and the context, so defining one message in this way is limiting. For example, a developer needs different feedback than an end user.
Instead, JSON Schema standardized the results that come back from a validation. This allows you to process the results to produce output that is appropriate for your audience. In theory libraries can be developed to produce error messaging for certain audiences. These would be decoupled from your validator library allowing you to more easily switch to another implementation in the future.
However, even the best error message producing libraries wouldn't solve the specific case presented in the original question. A library can't take a regular expression and produce a meaningful message. The good news is, JSON Schema provides an extension mechanism called vocabularies that you can use to create a custom keyword to annotate your schemas with the information that an output processor needs to produce a better error message. For example, the `errors` keyword in the original question would appear in the standard output results and can be used by an output processor as one of the ways it produces nice user facing error messages.
Unfortunately, no one has built one of these standard output processors yet, so you won't be able to pick one up off the shelf. It shouldn't be too hard to do, but you'd have to write it yourself. https://github.com/atlassian/better-ajv-errors is one of these output processor tools, but it uses ajv's proprietary output format rather than the standard format.
Both the standardized output format and JSON Schema Vocabularies are new in draft 2019-09 which has not seen big adoption so far. As time goes on, we expect to see more tools that make these kinds of customizations easy.
Problem
How to customise error message for invalid input? ``` { "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "properties": { "username": { "type": "string", "pattern": "^[A-Za-z0-9-_.]+$", "minLength": 3 }, "password": { "type": "string", "minLength": 8, "pattern": "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[a-zA-Z\\d\\W]$" } }, "required": [ "username", "password" ], "errors": [ { "property": "username", "message": "min 3 characters, do not use spaces or special characters" } ] } ``` For example, if username input is not of required min length or doesn't satisfy regex pattern, display one custom message `min 3 characters, do not use spaces or special characters`