Python Form Validation with Pydantic

Validate form data in Python using Pydantic v2 models with custom validators, nested model validation, error message customization, and JSON schema export.

PythonForm Validation

Code

snippet
from pydantic import BaseModel, EmailStr, field_validator

class LoginForm(BaseModel):
    email: EmailStr
    password: str

    @field_validator('password')
    @classmethod
    def validate_password(cls, v):
        if len(v) < 8:
            raise ValueError('Password must be at least 8 characters')
        if not any(c.isupper() for c in v):
            raise ValueError('Must contain uppercase')
        return v

try:
    form = LoginForm(email='[email protected]', password='Secret123')
except ValueError as e:
    print(f'Validation error: {e}')

What the code does

Python Form Validation with Pydantic keeps everything in the class LoginForm and the function validate_password.

BaseModel, EmailStr, field_validator are the only symbols borrowed from pydantic — the coupling is explicit and narrow. ValueError is the guard’s signal — thrown at the branch, before any partial work happens.

Points of care

  • External dependency: pydantic — install it before running the snippet.
  • The guard len(v) < 8 short-circuits the flow with an early raise when its condition holds.

Using it

The primary signature is def validate_password(cls, v)

The demo output is labeled (Validation error:), so every printed line maps back to its originating operation.

validate_password is what another module would consume; nothing else here is load-bearing for callers.

Key statements

def validate_password(cls, v):
    if len(v) < 8:
        raise ValueError('Password must be at least 8 characters')
    if not any(c.isupper() for c in v):
        raise ValueError('Must contain uppercase')
    return v
except ValueError as e:
    print(f'Validation error: {e}')

Interactive Tools for This Topic

FAQ

What happens on invalid input?
It throws `ValueError` before any real work runs, via the guard `len(v) < 8` — handle it at the call site or let it propagate deliberately.
Are there third-party dependencies?
`pydantic` — install it with the package manager before running.