0

Is it possible to validate the json data below, so that "info" can only be filled in when "name" is "a" otherwise it must be empty or null?

[
  {
    "name": "a",
    "info": "this is mandatory"
  },
  {
    "name": "b",
    "info": "validation must fail"
  }
]

the JSONSchema

{
 "title": "Array of things",
  "type": "array",
  "items": {
    "type": "object",
    "properties": {
      "name": {
        "type": "string",
        "enum": [
          "a",
          "b"
        ]
      },
      "info": {
        "type": "string"
      }
    }
  }
}

The json in an online editor

1 Answer 1

2

try this:

{
 "title": "Array of things",
  "type": "array",
  "items": {
   "type": "object",
   "properties":  {
      "name": {
         "type": "string",
        "enum": ["a", "b"]
      },
      "info" : {
         "type": ["string", "null"]         
      }
   },
   "required": ["name"],

   "oneOf": [
      {
         "properties": {
             "name": {"enum": ["a"] }
         },
         "required": ["info"]
      },
     {
         "properties": {
             "name": {"enum": ["b"] },
"info": {"enum": [null]}
         }         
      }
   ]
}
}
Sign up to request clarification or add additional context in comments.

1 Comment

This will work for draft-4, but if the library you have uses a newer draft like draft-7, you can use if/then/else (if you want to). I won't add an answer as you've already accepted this one.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.