Search code examples
jsonschemajson-schema-validatorjsonschema2pojo

Adding custom error messages in "anyOf" JSON Schema


I'm looking to add custom error messages to my JSON Schema on a bad validation in an "allOf". I have this which works (on a "not"):

"not": {
    "anyOf": [
      {
        "required": ["prop1"],
        "errorMessage": "Property 'prop1' is not allowed"
      },
      {
        "required": ["prop2"],
        "errorMessage": "Property 'prop2' is not allowed"
      }
    ]
}

And I get: "[$.content[0] should not be valid to the schema...<standard error message>..., Property 'prop1' is not allowed.

Great that works.

I'm trying to validate the max items of an array:

"if": {
  "properties": {
    "required": [
      "x"
    ]
  }
},
"then": {
   properties": {
      "actions": {
        "maxItems": 2,
        "errorMessage": "you can't have more than 3 items in the array if x is true."
      }
   }
},
"else": {
  "properties": {
      "actions": {
        "maxItems": 3,
        "errorMessage": "you can't have more than 2 items in the array if x is false."
      }
   }
}

The message I get upon validation failure:

[$.content[0].actions: there must be a maximum of 3 items in the array]

and

[$.content[0].actions: there must be a maximum of 2 items in the array].

I'm not looking to do said validation, this is just an example. I want the error message to also include: you can't have more than 2 items in the array if x is false.. Is this possible? I've tried several different things and it only seems to be possible when a "not" is involved like in the first code block. It seems that this is possible to do in the actual definition of the object declaration, but I need to do it in an "allOf".

Relevant POM versions:

<json-schema-validator.version>1.0.52</json-schema-validator.version>
<jsonschema2pojo.version>1.0.2</jsonschema2pojo.version>

TIA!


Solution

  • I managed to get a (hacky) workaround. If you add 2 "nots" you can utilise the "errorMessage" parameter and 1 not will negate the other:

                    "properties": {
                      "actions": {
                        "not": {
                          "not": {
                            "maxItems": 3,
                            "errorMessage": "You cannot have more than 3 items in the actions object for Line messaging."
                          }
                        }
                      }
                    }