简体   繁体   中英

Python validate date using pydantic to accept empty string

I'm using pydantic to validate data in AWS Lambda, I have a field for date that can accept either a valid date or empty string.

When I pass an empty string to that field 'date', it does not work and I get the following error :

pydantic.error_wrappers.ValidationError: 1 validation error for EmployeeInput
date
  invalid datetime format (type=value_error.datetime)

This is how I defined the model :

class EmployeeInput(BaseModel):
    last_name: str = ''
    first_name: str = ''
    date: Optional[datetime] = get_date_now()

I have tried to use Union[datetime, str] , it is now accepting empty string but does not validate date anymore.

How can I make my field accept both empty string '' and validate the content if its a proper date ?

Your first error is normal. Indeed, you ask for either a date, or None , but you pass a string, certainly, empty but a string nevertheless, so, you do not correspond to the scheme.

The solution I see to accept a date or an empty string only, would be to write your schema with an Union, and write your own validator as follows:

def date_validator(date):
    if not isinstance(date, datetime) and len(date) > 0:
        raise ValueError(
            "date is not an empty string and not a valid date")
    return date


class EmployeeInput(BaseModel):
    last_name: str = ''
    first_name: str = ''
    date: Union[datetime, str] = get_date_now()

    _date_validator = validator(
        'date', allow_reuse=True)(date_validator)

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