Implementing Data Validation

1. Validating Data Types

LayerMechanism
SchemaStrict column types
Domain typesCREATE DOMAIN with CHECK
ApplicationDTO with TypeScript / Pydantic / Bean Validation
API edgeJSON schema, OpenAPI

2. Enforcing Required Fields

MechanismDetail
NOT NULL constraintDB-level guarantee
DEFAULTAvoid NULLs by auto-fill
JSON schema requiredFor semi-structured
App validationFail fast at boundary

3. Implementing Range Validation

ToolExample
CHECK constraintCHECK (qty BETWEEN 1 AND 1000)
Range domainCREATE DOMAIN pct AS NUMERIC CHECK (VALUE BETWEEN 0 AND 100)
Range type (PG)NUMRANGE, TSTZRANGE
AppSchema validator min/max

4. Using Regular Expressions for Patterns

PatternUse
Email~* '^[^@\s]+@[^@\s]+\.[^@\s]+$'
Phone E.164~ '^\+[1-9]\d{7,14}$'
UUID~* '^[0-9a-f-]{36}$'
Slug~ '^[a-z0-9-]+$'
Warning: Regex validation is brittle for emails — use a library + verification flow for production.

5. Implementing Custom Validation Rules

MechanismDetail
CHECK with functionCHECK (is_valid_iban(iban))
BEFORE triggerRAISE EXCEPTION on bad data
EXCLUSION constraintNo overlapping schedules
App-sideCross-field, async lookups

6. Handling Validation Errors

ApproachDetail
Fail fastReject at API boundary with 400
Collect all errorsReturn list, not first failure
Field-level errorsPer-input message in response
Map DB error → user messageSQLSTATE → human-readable

7. Validating Relationships and References

ToolDetail
FOREIGN KEYHard reference check
DEFERRABLEAllow temporary inconsistency within tx
Cardinality checkTrigger limits children per parent
Cross-aggregateApp / saga responsibility

8. Implementing Server-Side Validation

LayerResponsibility
API gatewayAuth, rate limit, basic schema
ServiceBusiness rules, cross-resource invariants
DatabaseFinal source of truth — constraints + triggers
Never trust clientEven after client-side validation

9. Using Schema Validation

ToolUse
JSON SchemaAPI contracts, document DBs
MongoDB validator$jsonSchema on collection
Avro / ProtobufStrong typing, event streams
PG JSONB + checkCHECK (jsonb_matches_schema(...))

10. Balancing Validation vs Performance

Trade-offStrategy
Heavy CHECK on hot pathMove to async or background validation
Trigger overheadBatch validation; avoid per-row in hot loops
Functional indexesPre-compute expensive checks
Edge enforcementValidate once at write boundary