1

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 ?

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.