IC Improve Code Recipes

Recipe 8.2 · Python

DataAnnotations That Actually Run

The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.

Problem

You decorate a request class with [Required] and [StringLength], and in ASP.NET Core MVC the framework checks them for you. Then the same class is used in a console importer, a background job, or a minimal API endpoint that does not run model validation, and the attributes quietly do nothing. Cross-field rules, such as "end date after start date," are bolted on somewhere else.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

This looks right and is one of the most common validation bugs I find. Without the fourth argument, validateAllProperties, TryValidateObject only evaluates [Required]. [Range], [StringLength], [EmailAddress] and every custom attribute are skipped. Showing only the first error is a separate annoyance for the user.

Requirements: Python 3.12+. Install: pip install pydantic

Python Running validation but only showing the first error (p166_r8_2_validate_show_first_error_before.py)
"""Running validation but only showing the first error

Source: ImproveCode, Chapter 8, Recipe 8.2 "DataAnnotations That Actually Run"
Section: The way it's often written
Book page: 166  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
pydantic replaces Validator.TryValidateObject; the Web Forms label is a simple object.
"""

from typing import Any

from pydantic import BaseModel, ValidationError


def validate_and_show(model_type: type[BaseModel], data: dict[str, Any],
                      lbl_error: Any) -> None:
    results: list[dict[str, Any]] = []
    try:
        model_type.model_validate(data)
        ok = True
    except ValidationError as ex:
        results = ex.errors()
        ok = False
    if not ok:
        lbl_error.text = results[0]["msg"]

The improved recipe

The request class keeps its attributes, adds one custom attribute and implements IValidatableObject for the cross-field rule. A small static helper runs everything and returns the errors grouped by property, in the same shape ASP.NET Core uses for ValidationProblemDetails.

Requirements: Python 3.12+. Install: pip install pydantic email-validator

Python Declarative model validation with a custom rule and cross-field check (p166_r8_2_contract_request_model_validation.py)
"""Declarative model validation with a custom rule and cross-field check

Source: ImproveCode, Chapter 8, Recipe 8.2 "DataAnnotations That Actually Run"
Section: The improved recipe
Book page: 166-168  -- original C# listing
Converted from C# to Python.
pydantic replaces DataAnnotations: Field constraints/EmailStr/Literal for the
attributes, an AfterValidator for [NotInPast], a model_validator for IValidatableObject.
The clock comes from validation context instead of IServiceProvider.
"""

from collections.abc import Callable
from datetime import date, datetime, timezone
from typing import Annotated, Any, Literal

from pydantic import (AfterValidator, BaseModel, EmailStr, Field,
                      ValidationError, ValidationInfo, model_validator)


def _not_in_past(value: date, info: ValidationInfo) -> date:
    clock: Callable[[], datetime] = (
        (info.context or {}).get("clock") or (lambda: datetime.now(timezone.utc)))
    today = clock().astimezone(timezone.utc).date()
    if value < today:
        raise ValueError(f"{info.field_name} cannot be in the past.")
    return value


NotInPast = AfterValidator(_not_in_past)


class ContractRequest(BaseModel):
    customer_name: Annotated[str, Field(min_length=2, max_length=100)] = ""
    contact_email: Annotated[EmailStr, Field(max_length=254)]
    seats: Annotated[int, Field(ge=1, le=500)] = 0
    currency: Literal["USD", "EUR", "GBP"] = "USD"
    start_date: Annotated[date, NotInPast]
    end_date: date

    @model_validator(mode="after")
    def _check_dates(self) -> "ContractRequest":
        if self.end_date <= self.start_date:
            raise ValueError("End date must be after the start date.")
        return self


class ModelValidator:
    @staticmethod
    def validate(model_type: type[BaseModel], data: dict[str, Any],
                 context: dict[str, Any] | None = None) -> dict[str, list[str]]:
        if data is None:
            raise TypeError("data must not be None.")

        try:
            model_type.model_validate(data, context=context)
            return {}
        except ValidationError as ex:
            grouped: dict[str, list[str]] = {}
            for err in ex.errors():
                member = ".".join(str(p) for p in err["loc"])
                message = err.get("msg") or "Invalid value."
                messages = grouped.setdefault(member, [])
                if message not in messages:
                    messages.append(message)
            return grouped

How it works

ModelValidator.Validate always passes validateAllProperties: true, which is the one-line fix to the bug above. Errors without a member name, which happen when a class-level rule forgets to name one, go under an empty key so they are not lost. The dictionary drops straight into Results.ValidationProblem(errors) in a minimal API, or into a list on a console importer's error report.

AllowedValues is new in .NET 8, along with DeniedValues, Length (minimum and maximum for strings and collections) and Base64String. Range also gained MinimumIsExclusive and MaximumIsExclusive. Before these, every team wrote its own [InList] attribute.

The custom NotInPast attribute shows two habits worth copying. It returns success for values it does not understand, so it combines with [Required] instead of duplicating it. And it asks the ValidationContext for a TimeProvider, falling back to the system clock. Pass a service provider that holds a fake TimeProvider and your tests stop depending on today's date.

IValidatableObject.Validate handles rules that span properties. The framework only calls it when every property attribute has passed, so you can assume the individual fields are well formed inside it.

Variations and pitfalls

  • Nested objects are not validated. TryValidateObject does not walk into child objects or collections. Either validate them separately and prefix the keys (Lines[2].Quantity), or use the validator in Recipe 8.3, which makes nesting explicit.
  • [EmailAddress] is permissive on purpose. It checks for one @ with something on each side. That is fine. The only real proof of an e-mail address is a message that arrives. Do not paste in a 400-character regular expression.
  • [Required] on a non-nullable int does nothing. The value is always present, 0 by default. Use [Range], or make the property int? with [Required] if "not supplied" must be detectable.
  • Minimal APIs. ASP.NET Core 10 adds built-in validation for minimal APIs through AddValidation(). On .NET 8 and 9, call ModelValidator.Validate in an endpoint filter so every endpoint gets the same behavior.
  • Options classes. The same attributes validate configuration through ValidateDataAnnotations() and ValidateOnStart(), covered in Chapter 6.