opis/json-schema

[Question] - Documentation on $error in schemas

Opened this issue · 2 comments

CGSeb commented

Hi, I see that we can specify a $error in a schema, but I can't find any documentation about it and how to use it.

{
    "type": "object",
    "properties":  {
        "name": {
            "type": "string",
            "$error":  {
                 "type": "The name should be a string"
            }
        }
    }
}

Am I missing something?

Unfortunately we don't have docs for $error yet.
However, this comment contains an example #80 (comment)

$error can be a string or an object.
If it is a string then no matter what keyword has error the message will always be the same.

{
   "type": "number",
   "minimum": 18,
   "maximum": 65,
   "$error": "Number must be in range 18-65"
}

If schema is invalid the error will always be "Number must be in range 18-65".

If $error is an object, then the keys represent the keyword and the value the error message.

{
   "type": "number",
   "minimum": 18,
   "maximum": 65,
   "$error": {
       "minimum": "Too young",
       "maximum": "Too old"
   }
}

If the minimum keyword failed then the message is Too young, if the maximum keyword failed the message will be Too old. If other keyword failed (for example type) the default error message will be used. You can provide a custom fallback
if you are not interested in all properties.

{
   "type": "number",
   "minimum": 18,
   "maximum": 65,
   "$error": {
       "minimum": "Too young",
       "*": "Invalid number"
   }
}

If the minimum keyword failed then the message is Too young otherwise the message is Invalid number.

These are basic examples on how to use the $error keyword. Also keep in mind that this is something specific to opis/json-schema, it is an attempt at providing user defined error messages embedding them in json-schemas.

CGSeb commented

Ok thank you, I have a case with some anyOf and some const for a dropdown select and it yields at me for every line of the anyOf, but I will do some testing with what you just said :)