如何将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
相关产品推荐
相关产品推荐

