Why is `minLengh` not validating a missing property in JSON Schema?

553 Views Asked by At

I am trying to validate a json schema for my object. But If else is not getting executed for my object. So here in this example I want to check if Sale description is there when Sale service is 'Y' (Note, I want to execute if else for object inside object) because saleScheduling is inside Sale object.

  "Sale":{
   "type":"object",
   "properties":{
      "SaleScheduling":{
         "type":"object",
         "properties":{
            "SaleDescription":{
               "type":"string"
            },
            "SaleService":{
               "type":"string",
               "minLength":1,
               "enum":[
                  "Y",
                  "N"
               ]
            }
         },
         "if":{
            "properties":{
               "SaleService":{
                  "const":"Y"  //if this is Y, SaleDescription should be present
               }
            }
         },
         "then":{
            "properties":{
               "SaleDescription":{
                  "minLength":1
               }
            }
         },
         "else":{
            "properties":{
               "SaleDescription":{
                  
               }
            }
         },
         "required":[
            "SaleService"
         ]
      }
   },
   "required":[
      "SaleScheduling"
   ]
}
1

There are 1 best solutions below

7
On BEST ANSWER

In order to make a property required using JSON Schema, you need to use the required keyword. Your subschema in the else...

{
  "properties":{
    "SaleDescription":{
      "minLength":1
    }
}

This will only apply minLength if the property SalesDescription exists. If it does not exist, it will not cause an error. This is how applicability works on JSON Schema. properties applies subschemas to an object based on the keys. { "minLength": 1 } is itself a subschema, which is applied to a location in the instance.

This is an example of an X/Y problem. Your if/then is working correctly, but the then subschema isn't doing what you expect.