Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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": ""
}
like image 505
Ric Avatar asked Jul 20 '16 10:07

Ric


1 Answers

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.

like image 86
erosb Avatar answered Sep 28 '22 09:09

erosb