Validating input: check once at the boundary, then trust your types
Where to validate data, how to report every problem at once with field paths, and how to write error messages people can act on. With examples in Python.
Every program that's used by real people gets bad input: empty fields, typos, numbers in the wrong unit, a country spelled three different ways. Validation decides what happens next. Done well, the user fixes their input in one go and the rest of your code never sees bad data. Done badly, the same checks are scattered everywhere and some of them are missing.
Validate at the boundary
Picture your program as a building. Data comes in through a few doors: a web form, an API, a file import, a message from another system. Those doors are the boundary.
┌──────────────────── your code ────────────────────┐
form ──► │ validate ─► Shipment ─► pricing ─► lifecycle ─► … │
file ──► │ validate ─┘ │
API ──► │ validate ─┘ │
└───────────────────────────────────────────────────┘The rule: check everything at the door, then trust what's inside. At the boundary, raw data
(dicts, strings, CSV rows) becomes your own types (a Shipment, an Address). Once something is
a Shipment, every function can assume it's valid.
Why this matters:
- One place for every rule. "A parcel weighs at most 31.5 kg" lives in one function. Change it once and it's changed everywhere.
- Simpler code inside. Pricing doesn't check for an empty city. It can't be empty.
- Fewer bugs. Rules that are checked "everywhere" end up checked "almost everywhere".
This idea is sometimes called parse, don't validate: instead of checking a dict and passing the same dict on, turn it into a type that can only hold valid data.
Shape first, then values
Raw input can be wrong in two ways:
- Shape: the field is missing, or it's the wrong kind of thing (a number where you expected text, a string where you expected a list).
- Value: it's the right kind of thing but not allowed (an empty name, a weight of 0, an unknown country).
Check the shape before you look at the value. Otherwise value.strip() on a number crashes with
an AttributeError instead of producing a helpful error.
def read_text(data: Mapping[str, object], key: str) -> str | None:
value = data.get(key)
if value is None:
return error(key, "is required")
if not isinstance(value, str): # shape
return error(key, "must be text")
value = value.strip()
if not value: # value
return error(key, "must not be empty")
return valueCollect every error
Imagine filling in a form that tells you about one mistake at a time. You fix the postcode, submit, and now it complains about the phone number. Then the city. That's what "raise at the first error" feels like to a user.
Instead, keep going after a problem, write it down, and report the whole list at the end:
class ValidationError(Exception):
def __init__(self, errors: list[FieldError]) -> None:
super().__init__("; ".join(f"{e.field}: {e.message}" for e in errors))
self.errors = errors
def create_shipment(data):
errors: list[FieldError] = []
customer = read_customer(data, errors)
recipient = read_address(data, "recipient", errors)
parcels = read_parcels(data, errors)
if errors:
raise ValidationError(errors)
return Shipment(customer, recipient, parcels)Each helper records its problem and returns None, so the next helper still runs.
Field paths
Each error names its field with a path: recipient.city, parcels[2].height_cm. A form uses
the path to highlight the right input; an API returns it so the caller knows what to fix; an
import translates it into a spreadsheet column. Build paths as you go, passing the prefix down:
f"{prefix}.city", f"parcels[{index}]".
Tidy, then check
Users type " Utrecht " and "nl". Decide which differences don't matter (surrounding spaces,
the case of a country code) and normalise them before checking. Store the tidy value.
Be careful not to go further than that. Turning "Germny" into "DE" or rounding 12.505 to
12.51 hides a mistake that someone should fix.
Errors people can act on
A good error message answers two questions: where is the problem, and what would be accepted?
| Bad | Good |
|---|---|
invalid input | recipient.country: is not a country we deliver to |
ValueError | parcels[1].height_cm: must be between 1 and 120 |
row error | line 7, weight_kg: must be a number |
Speak the user's language. People editing a spreadsheet think in line numbers and column names, so
an import should translate parcels[0].weight_grams into "line 7, column weight_kg", and grams into
kilograms if that's what they typed.
Validation libraries
In real projects you'll often use a library for this: Pydantic in Python (FastAPI uses it), Zod in TypeScript. They do exactly what this guide describes: check shape and values, convert to typed objects, collect every error with its path. Writing it by hand once is the best way to understand what they do, and to know what to check when they don't do what you expected.
Questions and answers
- Where should input validation happen?
- At the boundary: where data enters your system from a form, an API request, a file or another service. Convert it into your own types there, and let the rest of the code trust those types instead of re-checking.
- Should validation stop at the first error?
- For input from people, no. Collect every problem and report them together, each with the field it's about, so the form or file can be fixed in one go. Inside your own code, failing fast on a broken assumption is fine.
Read next
- Invariants and all-or-nothing updates: keeping data consistent
Name the rules your data must always obey, enforce them in one place, validate everything before changing anything, keep history append-only, and test invariants with random operations.
- Python dataclasses, enums and datetimes: modelling a business domain
Model real business data in Python with dataclasses, frozen value objects, StrEnum for fixed choices, type hints checked by mypy, and timezone-aware datetimes.
- How to work with tickets and acceptance criteria as a junior developer
How to read a ticket, find what it doesn't say, ask good questions, and turn acceptance criteria into tests, with examples from realistic product tickets.