Validation System
DomusJS integrates Zod as the default schema validation library, making it easy to validate inputs, DTOs, and command/query payloads.
✅ Zod provides a fluent, type-safe way to define and check data shapes.
✅ DomusJS also includes built-in Express middleware to automatically validate incoming requests from params
, body
, or query
.
✅ You can swap in any other validation library if needed.
Why Zod?
Section titled “Why Zod?”- Fully TypeScript-native: great type inference.
- Simple API for defining schemas.
- Built-in support for nested objects, refinements, and transformations.
- Easy to plug into the request pipeline.
Example with Zod
Section titled “Example with Zod”Step 1: Define a Schema
Section titled “Step 1: Define a Schema”import { z } from 'zod';
export const RegisterUserSchema = z.object({ username: z.string().min(3), email: z.string().email(), password: z.string().min(8),});
Step 2: Use It in a Handler or Service
Section titled “Step 2: Use It in a Handler or Service”import { RegisterUserSchema } from './schemas/register-user.schema';
const result = RegisterUserSchema.safeParse(input);
if (!result.success) { throw new BadRequestError('Invalid input', 'VALIDATION_ERROR');}
const { username, email, password } = result.data;// proceed with the valid data
✅ This ensures inputs are validated before reaching the domain layer.
Built-in Express Validators
Section titled “Built-in Express Validators”DomusJS provides prebuilt middleware to validate incoming request parts automatically.
import { validateBody, validateQuery, validateParams } from '@domusjs/infrastructure';import { RegisterUserSchema } from './schemas/register-user.schema';
app.post('/auth/register', validateBody(RegisterUserSchema), (req, res) => {
// At this point, req.body is already validated const data = req.body;
// Implment the registration logic here});
✅ validateBody(schema)
→ validates req.body
✅ validateQuery(schema)
→ validates req.query
✅ validateParams(schema)
→ validates req.params
If validation fails, the middleware throws a BadRequestError
automatically.
Custom Validators
Section titled “Custom Validators”DomusJS does not enforce Zod — you can integrate your own validator by following the same middleware pattern.
Best Practices
Section titled “Best Practices”✅ Always validate external inputs before entering the domain layer.
✅ Use schemas for commands, queries, DTOs, and external API data.
✅ Keep validation and domain rules separate — they serve different purposes.
✅ For reusable validators, create a dedicated validators/
directory or module.