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

如何将Pydantic模型密码不匹配的校验错误绑定到指定字段

解决Pydantic密码匹配错误绑定到指定字段的问题

要把密码不匹配的错误绑定到confirm_password字段,无需使用模型级校验,直接给confirm_password字段添加校验器,在其中对比密码与确认密码即可,校验失败时错误会自动关联到该字段。

修改后的代码如下:

from pydantic import BaseModel, Field, field_validator, ValidationError

class RequestFile(BaseModel):
    password: str = Field(..., min_length=8, max_length=128)
    confirm_password: str = Field(..., min_length=8, max_length=128)

    @field_validator("password")
    def password_validate(cls, v: str) -> str:
        if not v.strip():
            raise ValueError("Password required")
        return v

    @field_validator("confirm_password")
    def confirm_password_validate(cls, v: str, values) -> str:
        if not v.strip():
            raise ValueError("Confirm Password Required")
        # 从已校验字段中获取密码值
        password = values.data.get("password")
        if password and v != password:
            raise ValueError("Passwords do not match")
        return v

# 测试示例
try:
    req = RequestFile(password="test1234", confirm_password="test12345")
except ValidationError as e:
    print(e.json())

关键说明:

  • 移除原有的模型级校验器@model_validator(mode="before"),改用confirm_password的字段校验器
  • 在confirm_password_validate中,通过values.data.get("password")获取已通过校验的密码值(Pydantic v2中values为ValidationInfo对象,data属性存储已校验字段)
  • 密码不匹配时抛出的ValueError会自动关联到confirm_password字段,和长度校验、非空校验的错误格式统一

测试输出的错误信息示例:

[
  {
    "type": "value_error",
    "loc": ["confirm_password"],
    "msg": "Passwords do not match",
    "input": "test12345",
    "ctx": {"error": "Passwords do not match"}
  }
]

内容的提问来源于stack exchange,提问作者Mr. Kenneth

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 13:42:36