Home > OS >  How to use min value with type datetime in Cerberus?
How to use min value with type datetime in Cerberus?

Time:02-17

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

CodePudding user response:

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
  • Related