You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Pydantic实现姓名字段、邮箱字段的首尾空格自动去除

问题原因

你现有写法的核心错误是将constr作为泛型参数嵌套在其他类型后方,不符合Pydantic的字段约束配置语法,因此无法实现去空格效果。

正确配置方式

分Pydantic不同版本给出可用写法:

Pydantic V2(当前主流版本)

V2推荐使用Annotated组合字符串约束实现通用去空格规则,特殊类型单独搭配验证器处理:

from pydantic import BaseModel, SecretStr, EmailStr, StringConstraints, field_validator
from typing import Annotated

# 可复用的自动去空格字符串类型
StrippedStr = Annotated[str, StringConstraints(strip_whitespace=True)]

class UserCreate(BaseModel):
    # 先去空格再做邮箱格式校验
    email: Annotated[EmailStr, StringConstraints(strip_whitespace=True)]
    password: SecretStr
    first_name: StrippedStr
    last_name: StrippedStr

    # 前置验证器处理密码字段的首尾空格
    @field_validator('password', mode='before')
    @classmethod
    def strip_password(cls, value):
        if isinstance(value, str):
            return value.strip()
        return value

Pydantic V1写法

V1直接使用constr定义去空格类型,搭配前置验证器处理特殊字段即可:

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

StrippedStr = constr(strip_whitespace=True)

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

    @validator('email', 'password', pre=True)
    def strip_special_fields(cls, value):
        if isinstance(value, str):
            return value.strip()
        return value

内容的提问来源于stack exchange,提问作者dataviews

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 01:24:03