5

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)]
dataviews
  • 2,466
  • 7
  • 31
  • 64
  • 1
    Replacing `str` with the `constr` class as the hint should work for first_name/last_name; I'm not sure if you can wrap EmailStr/SecretStr that way, in either case you could use a validator instead together with `.strip`. – MatsLindh Sep 09 '21 at 06:38

2 Answers2

6

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
Yaakov Bressler
  • 9,056
  • 2
  • 45
  • 69
4

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.address@example.com   ",
    password="   some password   ",
    first_name="   First   ",
    last_name="   Last   ",
)
print(user)
# email='email.address@example.com' 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.
Paul P
  • 3,346
  • 2
  • 12
  • 26