[Python] pydantic model validator raise ValueError to field

Discussão em 'Python' iniciado por Stack, Agosto 5, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to do a validation on passwords where if they dont match, return an error. But I want to assign the error to field.

    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) -> str:
    if not v.strip():
    raise ValueError("Confirm Password Required")
    return v

    @model_validator(mode="before")
    def check_passwords_match(cls, values):
    password = values.get("password")
    confirm_password = values.get("confirm_password")

    if password != confirm_password:
    raise ValueError("Passwords does not match")

    return values


    In the code above, when either password or confirm_password failed validation (char length), it pushes the ValueError to field password and confirm_password respectively. However, when they dont match, it returns the ValueError but not on any field. How to push the ValueError to either password or confirm_password? Preferrably in confirm_password

    Continue reading...

Compartilhe esta Página