Description
Standardize validation error
When using jsonschema in validating user's input (e.g. in a html form), usually we want to give users friendly/multilingual/custom error messages. Futhermore, the error message may include some validation params.
Take the minLength
keyword as example, two validation params are available for sure:
- the length of the input string ($a)
- the minLength defined in the schema ($b)
With those two params, we can form various error messages like:
- Need at least $b characters
- Need at least $b characters, $a given
- ... etc.
Considering the usage described above, I proposal to standarlize params that a validation error must give, including the type and the meaning. e.g.,
As for minLength
,
- the length of the input string (should be
number
) - the minLength defined in the schema (should be
number
)
As for minimum
,
- the actual input number (should be
number
) - the minimum defined in the schema (should be
number
)
and so on.
In a word, the proposal can be regarded as "Standardize and structuring the validation error".
A new keyword messages
Based on the structuralized error, I propose to add a new keyword, let me call it messages
. This keyword is used to define templates for formating errors. It looks like:
{
"type": "string",
"minLength": 2,
"messages": {
"default": "the string is wrong",
"minLength": "the string is too short, must have $a charaters"
}
}
There are two keys in the messages
keyword, default
and minLength
. When a validation error occurs, the validator should use corresponding error message template defined in the messages
keyword to format the error.
e.g., if the error is caused by minLength
keyword, then,
- template
minLength
in themessages
should be used. - If no corresponding template is defined, then the
default
template should be used. - If the
default
template isn't present, then validators can format the error as they want.
Without the proposed messages
keyword, it will be very hard for developers to format error messages as they want, especially in the circumstance that developers won't be able to get the validation params as mentioned above. By the way, error message are ususually tied closely to a specific schema, that's why I propose to embed messages
in the schema itself.
Finally, if there's a duplicate issue, please let me know, thanks.