Combining EmailStr with constr in pydantic 2.0
06:00 21 Aug 2023

we used pydantic's EmailStr and ConstrainedStr to standardize validation and transformation of email string in requests. It was done the following way:

class EmailApiField(ConstrainedStr, EmailStr):
    to_lower = True
    strip_whitespace = True

    @classmethod
    def __get_validators__(cls):
        yield from ConstrainedStr.__get_validators__()
        yield from EmailStr.__get_validators__()

and then it's used in our requests schemas definitions

class LoginReq(SchemaBase):
    email: EmailApiField

Now, I can't find a way to achieve the same with pydantic 2.0. Anyone? :)

I tried the following

EmailApiField = Annotated[
    EmailStr, BeforeValidator(constr(to_lower=True, strip_whitespace=True))
]

but constr cannot be used as Annotated metadata

python pydantic