'pydantic with removal of white space

I am trying to remove white space on the first name and last name field, as well as the email field. I am unable to get it to work.

from pydantic import BaseModel, UUID4, SecretStr, EmailStr, constr

class UserCreate(BaseModel):
    email: EmailStr[constr(strip_whitespace=True)]
    password: SecretStr[constr(strip_whitespace=True)]
    first_name: str[constr(strip_whitespace=True)]
    last_name: str[constr(strip_whitespace=True)]


Solution 1:[1]

It looks like EmailStr is stripping whitespaces for you, and you could use constr() with strip_whitespace=True directly instead of str:

from pydantic import BaseModel, SecretStr, EmailStr, constr

class UserCreate(BaseModel):
    email: EmailStr
    password: SecretStr
    first_name: constr(strip_whitespace=True)
    last_name: constr(strip_whitespace=True)

user = UserCreate(
    email="   [email protected]   ",
    password="   some password   ",
    first_name="   First   ",
    last_name="   Last   ",
)
print(user)
# email='[email protected]' password=SecretStr('**********') first_name='First' last_name='Last'
#
# Leading and trailing whitespaces removed in email, first_name, last_name.

print(f"'{user.password.get_secret_value()}'")
#'   some password   '
#
# However, not in password.

Solution 2:[2]

You could add custom configuration options in your model or baseclass:

class UserCreate(BaseModel):
    email: EmailStr
    password: SecretStr
    first_name: str
    last_name: str

    class Config:
        """Extra configuration options"""
        anystr_strip_whitespace = True  # remove trailing whitespace

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 ybressler_simon