A malformed payload that reaches your database is no longer an input problem. It is a data-integrity problem, and in a regulated firm that means it is a reporting problem waiting to surface at the worst moment.
Most validation I see in production is scattered across the request handler in a handful of if statements that grew one bug at a time. It works until it doesn’t: a client sends a currency code in lower case, an amount arrives as a string, a required field is simply absent, and the row lands in Postgres anyway because nothing at the edge said no. The fix is not more if statements. It is a single, explicit contract — a JSON Schema — that every payload has to satisfy before your handler touches it, backed by a database constraint for the day the schema is bypassed.
The schema is the contract, not a comment
The point of writing the schema as a standalone document — not as scattered decorators, not as a docstring — is that it becomes the single source of truth. The same file validates requests at runtime, generates the request section of your OpenAPI document, and gives your front-end team something authoritative to build against. Write it once in JSON Schema 2020-12 and everything downstream reads from it. This is the same discipline behind spec-first API development with OpenAPI 3.1: design the contract before the code, then hold the code to it.
Free · 4 minutes
When two of your systems disagree, do you know which one to believe?
Fourteen questions on ownership, lineage, and quality — the difference between a number on a dashboard and a number you could defend. Banded finding on screen, full sheet by email.
Here is a schema for a payment instruction. It covers required fields, types, an enum, string formats, a regex-constrained IBAN, and — the part most hand-rolled validators never get right — a conditional rule: an international payment must carry a BIC.
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://example.com/schemas/payment-instruction.json",
"title": "PaymentInstruction",
"type": "object",
"additionalProperties": false,
"required": ["amount", "currency", "debtor_account", "creditor_account", "reference", "payment_type"],
"properties": {
"amount": { "type": "number", "exclusiveMinimum": 0, "multipleOf": 0.01 },
"currency": { "type": "string", "enum": ["EUR", "GBP", "USD"] },
"debtor_account": { "type": "string", "pattern": "^[A-Z]{2}[0-9]{2}[A-Z0-9]{11,30}$" },
"creditor_account": { "type": "string", "pattern": "^[A-Z]{2}[0-9]{2}[A-Z0-9]{11,30}$" },
"reference": { "type": "string", "minLength": 1, "maxLength": 140 },
"payment_type": { "type": "string", "enum": ["domestic", "international"] },
"bic": { "type": "string", "pattern": "^[A-Z]{6}[A-Z0-9]{2}([A-Z0-9]{3})?$" },
"requested_execution_date": { "type": "string", "format": "date" }
},
"if": {
"properties": { "payment_type": { "const": "international" } }
},
"then": {
"required": ["bic"]
}
}
Two choices there earn their keep. additionalProperties: false rejects anything you did not name, so a client cannot smuggle an extra field past you into a permissive ORM. And if/then encodes the conditional requirement declaratively — no branching logic in the handler, no forgetting to update it when a second rule appears.
Enforcing it at the edge with Express and Ajv
Ajv is the standard validator for the Node ecosystem, and 2020-12 support ships in the box — you import the dialect-specific build. Add ajv-formats for the date, date-time, email and uri formats, which core Ajv leaves unimplemented by design. Compile the schema once at start-up, then reuse the compiled function as middleware.
// validate-payment.mjs
import { readFileSync } from "node:fs";
import Ajv2020 from "ajv/dist/2020.js";
import addFormats from "ajv-formats";
const schema = JSON.parse(
readFileSync(new URL("./payment-instruction.schema.json", import.meta.url))
);
const ajv = new Ajv2020({ allErrors: true });
addFormats(ajv);
const validate = ajv.compile(schema);
// Express middleware: reject bad input before the handler runs.
export function validatePayment(req, res, next) {
if (validate(req.body)) return next();
return res.status(422).json({
error: "payload_validation_failed",
details: validate.errors.map((e) => ({
field: e.instancePath || e.params.missingProperty || "(root)",
rule: e.keyword,
message: e.message
}))
});
}
Wire it in front of the route — app.post("/payments", validatePayment, createPayment) — and createPayment can assume its input is well-formed. allErrors: true returns every failure at once rather than stopping at the first, so a client fixing a form gets the whole list, not a frustrating one-at-a-time drip. If you are still catching validation blow-ups downstream, that is a symptom worth reading alongside unhandled promise rejections crashing your Express API: both come from letting bad state travel further into the request than it should.
The same discipline in FastAPI and Pydantic
If your stack is Python, Pydantic 2 gives you the same guarantees with the model as the schema. FastAPI validates the request body against the model automatically and returns a structured 422 on failure — you write no validation code in the handler at all. The one thing worth doing by hand is the conditional rule, which a model_validator expresses cleanly.
from decimal import Decimal
from typing import Literal, Optional
from fastapi import FastAPI
from pydantic import BaseModel, ConfigDict, Field, model_validator
IBAN = r"^[A-Z]{2}[0-9]{2}[A-Z0-9]{11,30}$"
BIC = r"^[A-Z]{6}[A-Z0-9]{2}([A-Z0-9]{3})?$"
class PaymentInstruction(BaseModel):
# Reject unexpected fields, mirroring additionalProperties: false.
model_config = ConfigDict(extra="forbid")
amount: Decimal = Field(gt=0)
currency: Literal["EUR", "GBP", "USD"]
debtor_account: str = Field(pattern=IBAN)
creditor_account: str = Field(pattern=IBAN)
reference: str = Field(min_length=1, max_length=140)
payment_type: Literal["domestic", "international"]
bic: Optional[str] = Field(default=None, pattern=BIC)
@model_validator(mode="after")
def bic_required_for_international(self) -> "PaymentInstruction":
if self.payment_type == "international" and self.bic is None:
raise ValueError("bic is required for international payments")
return self
app = FastAPI()
@app.post("/payments", status_code=201)
def create_payment(instruction: PaymentInstruction) -> dict:
# instruction is already validated; persist it here.
return {"status": "accepted"}
Pydantic can also emit the JSON Schema for this model with PaymentInstruction.model_json_schema(), so even here the schema stays generated and inspectable rather than drifting out of sync with the code. If you are starting from a clean slate, the wiring sits naturally on top of a baseline FastAPI project with Pydantic settings, routers and lifespan.
The belt-and-braces database constraint
Edge validation is the front door, not the only door. Bulk imports, a background job, a migration script, a second service writing to the same table — any of these can insert a row without passing through your handler. So the invariants that genuinely must never be violated belong in the database as well, expressed as CHECK constraints. They are cheap, they are enforced by Postgres itself, and they turn a silent bad row into a loud rejected write.
ALTER TABLE payment_instruction
ADD CONSTRAINT amount_positive
CHECK (amount > 0),
ADD CONSTRAINT currency_allowed
CHECK (currency IN ('EUR', 'GBP', 'USD')),
ADD CONSTRAINT iban_shape
CHECK (debtor_account ~ '^[A-Z]{2}[0-9]{2}[A-Z0-9]{11,30}$'
AND creditor_account ~ '^[A-Z]{2}[0-9]{2}[A-Z0-9]{11,30}$'),
ADD CONSTRAINT bic_for_international
CHECK (payment_type <> 'international' OR bic IS NOT NULL);
Note the conditional constraint uses the same logic the schema does — payment_type <> 'international' OR bic IS NOT NULL is the SQL way of saying “if international, then BIC”. You are stating the same invariant twice, in two layers, on purpose. The schema gives callers fast, detailed feedback; the constraint guarantees the invariant holds regardless of how a row arrives.
Keeping the schema honest
A schema is only a single source of truth if you treat it as one. Keep the .schema.json file in version control next to the code, not pasted into three services. Reference it from your OpenAPI document by $ref rather than copying it. Add a test that feeds the schema a few known-bad payloads and asserts they are rejected, so a well-meaning refactor cannot quietly loosen it. And when a rule changes, change it in the schema first and let the constraint and the docs follow — the same principle that governs schema-validating and policy-checking every agent tool call: the boundary is where you decide what is allowed, and everything inside gets to trust that decision.
Validation is not a nicety you bolt on when you have time. It is the line between data you can report on and data you have to explain. Draw it at the edge, and draw it again at the table.
Build and rescue work
Hands-on delivery of this kind is handled by Sixteen Pillars Studio.
Free interactive tool
Interactive deadline calculator
Check which regulations apply to you and when
Regulation across the EU, UK, US and Asia-Pacific has moved considerably in the past eighteen months, and several headline dates have shifted more than once. Twelve questions, about three minutes.
Results are shown on screen — no email required. A dated summary is available to download, and can be sent on if that's more useful. What we do with your answers.
Governance is what happens when nobody is watching.
Policies are easy. Consistent decision-making is harder. Understand where governance exists and where it has quietly become assumed.
Full Governance by Sixteen Pillars
Govern your business. Prove your compliance.
A board assurance cockpit for EU-regulated financial firms — tamper-evident, hash-chained proof of governance across DORA, GDPR, NIS2, ISO 27001, the EU AI Act and MiCA. In development.
See what's coming