Dataclass With Pydantic Validation

Define a dataclass with Pydantic for runtime validation type coercion and JSON serialization.

PythonForm Validation

Code

pythonsnippet
10 lines
from pydantic import BaseModel, Field, validator
class User(BaseModel):
    email: str
    age: int = Field(ge=18, le=120)
    tags: list[str] = Field(default_factory=list)
    @validator('email')
    def validate_email(cls, v):
        if '@' not in v:
            raise ValueError('invalid email')
        return v.lower()

Inside the snippet

Dataclass With Pydantic Validation is built around the class User and the function validate_email.

Reach for pydantic and what you get is BaseModel, Field, validator — that is the whole API contact area. When the guard condition holds, ValueError is thrown rather than a bogus value returned.

What to watch for

  • External dependency: pydantic — install it before running the snippet.
  • The guard '@' not in v short-circuits the flow with an early raise when its condition holds.

Using it

The entry-point signature is def validate_email(cls, v)

Import validate_email from the file and call it — the rest of the code is implementation detail.

Key statements

def validate_email(cls, v):
    if '@' not in v:
        raise ValueError('invalid email')
    return v.lower()

Interactive Tools for This Topic

FAQ

Is there a failure path for bad input?
The code throws `ValueError` — the guard `'@' not in v` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
Does this require external packages?
Yes — `pydantic`. Add it to your project before running the snippet.