Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use min value with type datetime in Cerberus?

I want validate a field with one value greater or equal 01/01/1900 in type datetime in Cerberus, but not works this way:

from cerberus import Validator 
from datetime import datetime
    
v = Validator()
schema = {
    "birthdate": {
        "type": "datetime",
        "required": True,
        "min": datetime(1900, 1, 1)
    }
}
document_valid = {'birthdate': '05/03/1900'}
document_invalid = {'birthdate': '05/03/1800'}

print(v.validate(document_valid, schema)) # I want this True
print(v.validate(document_invalid, schema)) # I want this False

Anyone could help me?

I’m using this version to Cerberus: Cerberus==1.3.4

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your approach is not false, just missing a decisive compoenent – which is to account for the date-format.

try this:

from cerberus import Validator 
from datetime import datetime   

v = Validator()
to_date = lambda s: datetime.strptime(s, '%d/%m/%Y') # date-formatting

schema = {
    "birthdate": {
        "type": "datetime",
        "required": True,
        'coerce': to_date,
        "min": datetime(1900, 1, 1)
    }
}
document_valid = {'birthdate': '05/03/1900'}
document_invalid = {'birthdate': '05/03/1800'}

print(v.validate(document_valid, schema)) # I want this True
print(v.validate(document_invalid, schema)) # I want this False
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading