IC Improve Code Recipes

Recipe 8.3 · Python

A Small Reusable Validator

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

DataAnnotations are good for field-level rules on simple types. They get awkward when rules depend on other services, apply only in some cases, or need to read like business sentences. Teams then fall back to a long Validate() method of nested if statements that returns the first error it finds, and every class does it differently.

The way it's often written

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

The result is HTML in a string, so it cannot be shown in an API response or a log without stripping tags, and nothing ties a message to the field it belongs to. I have seen this exact shape in more Web Forms code-behind files than I can count.

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Validation that concatenates HTML error strings (p169_r8_3_html_error_string_validation_before.py)
"""Validation that concatenates HTML error strings

Source: ImproveCode, Chapter 8, Recipe 8.3 "A Small Reusable Validator"
Section: The way it's often written
Book page: 169-170  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
OrderRequest is duck-typed (Any) as in the original fragment.
"""

from typing import Any


def validate(o: Any) -> str:
    msg = ""
    if o.customer_id is None or o.customer_id.strip() == "":
        msg += "Customer is required<br/>"
    if o.quantity < 1:
        msg += "Quantity must be positive<br/>"
    if o.rush and o.ship_by is None:
        msg += "Ship-by date required for rush<br/>"
    return msg

The improved recipe

A base class of about sixty lines gives you a consistent shape: rules are declared in the constructor, every rule runs, and the result is a list of property/message pairs.

Requirements: Python 3.12+. Standard library only, nothing to install.

Python A small reusable rule-based validator with nested collections (p170_r8_3_reusable_rule_validator.py)
"""A small reusable rule-based validator with nested collections

Source: ImproveCode, Chapter 8, Recipe 8.3 "A Small Reusable Validator"
Section: The improved recipe
Book page: 170-172  -- original C# listing
Converted from C# to Python.
Plain Python generics (PEP 695) and lambdas replace Func<T,...> delegates;
records become frozen dataclasses.
"""

from collections.abc import Callable, Iterable, Sequence
from dataclasses import dataclass
from datetime import date


@dataclass(frozen=True)
class ValidationError:
    property: str
    message: str


class ValidationOutcome:
    def __init__(self, errors: Sequence[ValidationError]) -> None:
        self._errors = tuple(errors)

    @property
    def errors(self) -> Sequence[ValidationError]:
        return self._errors

    @property
    def is_valid(self) -> bool:
        return len(self._errors) == 0

    def to_dictionary(self) -> dict[str, list[str]]:
        result: dict[str, list[str]] = {}
        for e in self._errors:
            result.setdefault(e.property, []).append(e.message)
        return result


class Validator[T]:
    def __init__(self) -> None:
        self._rules: list[Callable[[T], ValidationError | None]] = []

    def validate(self, instance: T) -> ValidationOutcome:
        if instance is None:
            raise TypeError("instance must not be None.")
        errors = [e for rule in self._rules
                  if (e := rule(instance)) is not None]
        return ValidationOutcome(errors)

    def must[P](self, property: str, selector: Callable[[T], P],
                is_valid: Callable[[P], bool], message: str,
                when: Callable[[T], bool] | None = None) -> None:
        self._rules.append(
            lambda x: ValidationError(property, message)
            if (when is None or when(x)) and not is_valid(selector(x))
            else None)

    def not_empty(self, property: str, selector: Callable[[T], str | None],
                  when: Callable[[T], bool] | None = None) -> None:
        self.must(property, selector,
                  lambda v: v is not None and v.strip() != "",
                  f"{property} is required.", when)

    def max_length(self, property: str, selector: Callable[[T], str | None],
                   max_len: int) -> None:
        self.must(property, selector,
                  lambda v: v is None or len(v) <= max_len,
                  f"{property} must be {max_len} characters or fewer.")

    def nested[C](self, property: str,
                  selector: Callable[[T], Iterable[C] | None],
                  child_validator: "Validator[C]") -> None:
        if child_validator is None:
            raise TypeError("child_validator must not be None.")

        def rule(x: T) -> ValidationError | None:
            for i, child in enumerate(selector(x) or []):
                errors = child_validator.validate(child).errors
                if errors:
                    first = errors[0]
                    return ValidationError(
                        f"{property}[{i}].{first.property}", first.message)
            return None

        self._rules.append(rule)


@dataclass(frozen=True)
class OrderLine:
    sku: str
    quantity: int


@dataclass(frozen=True)
class OrderRequest:
    customer_id: str | None
    rush: bool
    ship_by: date | None
    lines: Sequence[OrderLine] | None


class OrderLineValidator(Validator[OrderLine]):
    def __init__(self) -> None:
        super().__init__()
        self.not_empty("Sku", lambda x: x.sku)
        self.max_length("Sku", lambda x: x.sku, 20)
        self.must("Quantity", lambda x: x.quantity,
                  lambda q: 1 <= q <= 1000,
                  "Quantity must be between 1 and 1000.")


class OrderRequestValidator(Validator[OrderRequest]):
    def __init__(self) -> None:
        super().__init__()
        self.not_empty("CustomerId", lambda x: x.customer_id)
        self.must("ShipBy", lambda x: x.ship_by,
                  lambda d: d is not None,
                  "A ship-by date is required for rush orders.",
                  when=lambda x: x.rush)
        self.must("Lines", lambda x: x.lines,
                  lambda l: l is not None and len(l) > 0,
                  "At least one order line is required.")
        self.nested("Lines", lambda x: x.lines, OrderLineValidator())

How it works

Each rule is a function from the object to either an error or null. Validate runs every rule, so the user sees all problems at once instead of fixing them one round trip at a time. Must is the general building block; NotEmpty and MaxLength are thin wrappers that keep the messages consistent across the application. The when parameter covers conditional rules like the rush-order date without an if in sight.

Nested validates child collections and reports the first failing child with an indexed path, Lines[2].Quantity, which a front end can map back to a grid row. Reporting only the first child error keeps a 5,000-line import from producing 5,000 messages; change it to SelectMany if you want them all.

ValidationOutcome.ToDictionary returns the same shape as Recipe 8.2, so DataAnnotations results and validator results can be merged and returned the same way. Validators have no state beyond their rule list, so register them as singletons.

Variations and pitfalls

  • Use nameof, not string literals. Property names in messages and keys then survive refactoring.
  • Async rules. "Customer exists" or "SKU is active" needs a database call. Don't make the whole validator async for one rule. Run cheap shape checks first with this class, and check existence in the application service, where the repository is already at hand.
  • FluentValidation. If you need localization, rule sets, or async rules everywhere, FluentValidation (FluentValidation on NuGet) is the mature version of this idea, and the rules translate almost line for line: RuleFor(x => x.Sku).NotEmpty().MaximumLength(20). I use the small class when a project needs a dozen validators and no new dependency.
  • Don't return HTML. Messages are plain text. The UI decides how to show them.