tdegrunt / jsonschema

JSON Schema validation
Other
1.83k stars 263 forks source link

How to enforce `enum` validation on a specific property? #369

Closed aMacDawg closed 2 years ago

aMacDawg commented 2 years ago

Use-case: a property channelType can only expect the enums 'youtube' and 'twitch', any other values to the channelType key should return a validation error.

JSON Schema snippet:

let schema = { //...trunc
"properties": {
        "channelType": {
            "type": "string",
            "default": "",
            "title": "The channelType Schema",
            "items": {
                "type": "string",
                "enum": [
                    "youtube",
                    "twitch"
                ]
            }
        }
//...trunc
}

sample code:

var validator = new Validator();
//req.query is the json obj formatted by express.js from inbound http requests
var result = validator.validate(req.query, schema, {nestedErrors: true});

Actual outcome: the channelType value could equal anything else ('facebook', 'sesame-street') and the validator will not return an error as expected

According to this stackoverflow post, the schema is formatted correctly for enums, and the npm-jsonschema docs did not specifically reference handling enums

aMacDawg commented 2 years ago

Ok, I had to do word salad with my own question, but found another stackoverflow post that got closer to what I was trying to get at - validation on a string field as opposed to validation on an array field which is what the enum approach seems to be for.

tl;dr - this works:

"channelType": {
            "type": "string",
            "default": "",
            "title": "The channelType Schema",
            "oneOf": [
                {"enum": ["youtube", "twitch"]}
            ]
        }

Closing this 🎉