简体   繁体   中英

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

Your approach is not false , just missing a decisive component - 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

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