Search code examples
pythonjsonschema

Validate jsonschema date format


I'm trying to validate the date property of a json object in python.

# Define JSON object
json_object = {
    "date": "21ducn23-dsfsd-ds",
    "age": 30
}

# Define JSON schema with date format
json_schema = {
    "type": "object",
    "properties": {
        "date": {"type": "string", "format": "date"},
        "age": {"type": "integer"},
    },
    "required": ["date", "age"],
    }
} 

# Validate JSON object against schema
jsonschema.validate(instance=json_object, schema=json_schema)

But as long as the date field is a string the validation comes through successfully.

I have read several answers to similar questions suggesting that format is annotation only. It seems that the documentation suggests otherwise but I may be missing something.

What can I do to get this to work without defining a regex expression for the date property?

I'm using jsonschema==4.21.1 and jsonschema-specifications==2023.12.1


Solution

  • From the documentation you linked:

    By default, format is just an annotation and does not effect validation. Optionally, validator implementations can provide a configuration option to enable format to function as an assertion rather than just an annotation.

    To do that in Python using jsonschema, you need to hook a format-checking object into the Validator.

    So just add format_checker=jsonschema.FormatChecker() to your validate call:

    from jsonschema import FormatChecker
    
    jsonschema.validate(
        instance=json_object, schema=json_schema, format_checker=FormatChecker()
    )
    

    It will then raise an error:

    jsonschema.exceptions.ValidationError: '21ducn23-dsfsd-ds' is not a 'date'
    
    Failed validating 'format' in schema['properties']['date']:
        {'format': 'date', 'type': 'string'}
    
    On instance['date']:
        '21ducn23-dsfsd-ds'