简体   繁体   中英

unable to use date validation in jsonschema

I am unable to use "date" for type validation in jsonschema

myschema = {
    "$schema": "http://json-schema.org/draft-04/schema#",
    "type": "object",
    "self": {
        "primary_key": ["email"]
    },
    "properties": {
        "email": {
            "pattern": "[^@]+@[^@]+\.[^@]+"
        },
        "dob": {
            "description": "Date of Birth YYYY-MM-DD",
            "type": "date"
        }
    }
}

When I execute the code below using above schema

from jsonschema import validate
validate({ "dob": "2001-02-30"}, myschema)

following error trace is obtained

Unhandled Exception: 'date' is not valid under any of the given schemas

Failed validating 'anyOf' in schema['properties']['properties']['additionalProperties']['properties']['type']:
    {'anyOf': [{'$ref': '#/definitions/simpleTypes'},
               {'items': {'$ref': '#/definitions/simpleTypes'},
                'minItems': 1,
                'type': 'array',
                'uniqueItems': True}]}

On instance['properties']['dob']['type']:
    'date'

Update: It seems date is a format and not type but still it is letting me key in an invalid date. I can clearly see in jsonschema code that it tries to parse it using datetime but I am unable to hit breakpoint in there.

The date should be used as a "format" , not "type":

"dob": {
    "description": "Date of Birth YYYY-MM-DD",
    "type": "string", 
    "format": "date"
}

Then, to check the format, use:

from jsonschema import validate, FormatChecker

validate({"dob": "2001-02-30"}, myschema, format_checker=FormatChecker()) 

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