Overview
Validation in Elysia uses TypeBox schemas to define expected data shapes. When validation fails, Elysia returns a 400 error with detailed information about what went wrong.Schema types
Elysia uses TypeBox’st namespace for schema definitions.
Primitives
Objects
Define object structures:Arrays
Validate arrays and their items:Optional fields
Make properties optional:Nested objects
Create complex nested structures:Validation targets
Validate different parts of the request:Body validation
Query validation
Params validation
Headers validation
Cookie validation
Response validation
Validate responses to ensure API consistency:Advanced types
String formats
Validate string patterns:String constraints
Add min/max length and patterns:Numeric constraints
Set boundaries for numbers:Enums
Restrict values to a specific set:Union types
Allow multiple types:Intersections
Combine multiple schemas:File upload validation
Validate file uploads:Reusable schemas
Define schemas once and reuse them:Model definition
Register models globally:Error handling
Validation errors are automatically handled:Custom error messages
Provide custom error messages:Type inference
Elysia automatically infers TypeScript types from schemas:Guard and group validation
Apply validation to multiple routes:Best practices
Always validate user input
Always validate user input
Never trust client data. Always validate body, query, and params for user-facing endpoints.
Use specific types
Use specific types
Prefer specific types like
t.Integer() over t.Number(), and use format validators for strings.Reuse schemas
Reuse schemas
Define common schemas once and reuse them across routes using models.
Validate responses in development
Validate responses in development
Enable response validation during development to catch API contract violations early.
Provide clear error messages
Provide clear error messages
Use custom error messages to help API consumers understand validation failures.
Common patterns
- Pagination
- Search filters
- Partial updates
Next steps
Type system
Learn about Elysia’s type system
Error handling
Handle validation errors gracefully