T
T
tjarrow2021-10-05 13:30:39
JSON
tjarrow, 2021-10-05 13:30:39

How to correctly display JSON schema validation errors for the anyOf key?

There is a JSON schema with the following fragment:

{
"required": [
    "label",
    "resource_type",
    "category"
  ],
"properties": {
...
},
"anyOf": [
    {
      "properties": {
        "resource_type": { "enum": ["phone"] },
        "phone": {
          "minLength": 1
        }
      },
      "required": ["phone"]
    },
    {
      "properties": {
        "resource_type": {
          "enum": [
            "audio", "pdf", "url", "video"
          ]
        },
        "url": {
          "minLength": 1
        }
      },
      "required": ["url"]
    },
{
      "properties": {
        "resource_type": { "enum": ["html"] },
        "html_content": {
          "minLength": 1
        }
      },
      "required": ["html_content"]
    },
    {
      "properties": {
        "resource_type": { "enum": ["media_resource"] },
        "media_resource_uuid": {
          "minLength": 1
        }
      },
      "required": ["media_resource_uuid"]
    }
  ]
}
}


The point is to set a particular field from the properties of the schema as required depending on the value of the resource_type field. For example, if resource_type: "phone", then the phone field from properties is required. Example of a valid object:

{
        "label" : "Test label",
        "phone" : "112",
        "resource_type" : "phone",
        "description" : "Test desc",
        "category" : "Test category"
    }


If you make the "phone" field empty, an error occurs that affects all fields from anyOf:


Message:
String '' is less than minimum length of 1.
Schema path:
#/anyOf/0/properties/phone/minLength

Message:
Value "phone" is not defined in enum.
Schema path:
#/anyOf/3/properties/resource_type/enum

Message:
Required properties are missing from object: media_resource_uuid.
Schema path:
#/anyOf/3/required

Message:
Required properties are missing from object: html_content.
Schema path:
#/anyOf/2/required

Message:
Required properties are missing from object: url.
Schema path:
#/anyOf/1/required


How can I update the schema so that the error only displays information about a specific anyOf (in this case, with the "phone" field), and not for all fields at once?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question