Skip to content

Proposal: Standardize validation error and introduce new keyword messages #1241

Closed
@TeCHiScy

Description

@TeCHiScy

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:

  1. the length of the input string ($a)
  2. the minLength defined in the schema ($b)

With those two params, we can form various error messages like:

  1. Need at least $b characters
  2. Need at least $b characters, $a given
  3. ... 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,

  1. the length of the input string (should be number)
  2. the minLength defined in the schema (should be number)

As for minimum,

  1. the actual input number (should be number)
  2. 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 the messages 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions