简体   繁体   中英

json schema validation using patternProprties with tv4

I have a json like:

{"post": {"someKey": {"anotherKey":"anotherValue"}}}

and where the first key is a valid http method and can be either of - post, get etc all valid http method at runtime.

Here is my schema

var schema = {
    "type": "object",
    "patternProperties": {
        "^[a-z]+$": {
            'properties': {
              "type": "object",
              'properties': {
                'someKey':{
                    'type': 'object',
                    'properties': {
                      'anotherKey': {'type': 'string'},
                    }
                }
            }
        }
      }
   }
}

var valid = { "post": {"mkey":"myvalue"}}; //This is getting passed but I know that is wrong
var invalid = { "1": {"mkey":"myvalue"}}; //This is passed but actually it should fail

console.log(tv4.validateMultiple(invalid, schema));

Can some one help?

I figured out:

{
    'type': 'object',
    'patternProperties': {
        '^(POST|GET|DELETE|HEAD|PATCH|HEAD|PUT)$': {
            'additionalProperties': false,
            'type': 'object',
            'required': ['someKey'],
            'properties': {
                'someKey': {
                    'type': 'string'
                }
            }
        }
    }
}

Here, things to note: 1.'additionalProperties': false is important for patternProperties 2. As per JSON Schema spec, you cannot have a case insensitive match and hence all are in upper case

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM