Ric Ric - 4 months ago 56
JSON Question

Ensure one property is not empty in JSON schema

For the given schema below, is it possible to ensure that at least one property contains a value (ie, minLength is 1):

{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"fundRaiseId": {
"type": "string"
},
"productTypeId": {
"type": "string"
},
"businessLineId": {
"type": "string"
}
}
}


So this would pass validation:

{
"fundRaiseId": "x"
}


And this would fail as no values are present:

{
"fundRaiseId": "",
"productTypeId": "",
"businessLineId": ""
}

Answer

I would try something like

{
    "allOf": [{
        "type": "object",
        "properties": {
            "fundRaiseId": {
                "type": "string"
            },
            "productTypeId": {
                "type": "string"
            },
            "businessLineId": {
                "type": "string"
            }
        }
    }, {
        "anyOf": [{
            "properties": {
                "fundRaiseId": {
                    "$ref": "#/definitions/nonEmptyString"
                }
            }
        }, {
            "properties": {
                "productTypeId": {
                    "$ref": "#/definitions/nonEmptyString"
                }
            }
        }, {
            "properties": {
                "businessLineId": {
                    "$ref": "#/definitions/nonEmptyString"
                }
            }
        }]
    }],
    "definitions": {
        "nonEmptyString": {
            "type": "string",
            "minLength": 1
        }
    }
}

Explanation: the JSON to be validated should conform to 2 root-level schemas, one is your original definition (3 string properties). The other one contains 3 additional sub-schemas, each defining one of your original properties as non-empty string. These are wrapped in an "anyOf" schema, so at least one of these should match, plus the original schema.

Comments