Validation
Validation is a critical part of any backend system — it ensures that only valid, meaningful data enters your domain, preventing inconsistencies, errors, and security issues.
DomusJS encourages explicit, layered validation that distinguishes between:
- Infrastructure-level validation (requests, APIs, DTOs).
- Domain-level validation (inside entities, value objects, services).
Let’s break it down.
Where Should You Validate?
Section titled “Where Should You Validate?”Infrastructure-Level Validation
Section titled “Infrastructure-Level Validation”This happens at the edge of the system, before data touches the domain layer.
Examples:
- Validating request bodies in Express using a schema (e.g., Zod, Joi).
- Checking input types, formats, required fields in DTOs (Data Transfer Objects).
Purpose:
✅ Provide fast feedback to clients.
✅ Filter out obviously bad requests.
✅ Avoid unnecessary domain work.
Domain-Level Validation
Section titled “Domain-Level Validation”This happens inside your domain, ensuring business rules are upheld.
Examples:
- An
Email
value object checks for a valid email format. - An
Order
aggregate ensures no payments are processed for an empty order. - A
User
entity enforces username uniqueness.
Purpose:
✅ Protect core business rules.
✅ Ensure consistency even if other systems bypass the outer layers (e.g., direct calls, integrations).
Example: Combining Both Levels
Section titled “Example: Combining Both Levels”// Infrastructure layerconst schema = z.object({ email: z.string().email(), password: z.string().min(8),});
const validated = schema.parse(req.body);
// Domain layerconst email = new Email(validated.email); // Value object validates furtherconst user = new User(id, email, validated.password);
✅ This ensures:
- The infrastructure filters bad requests quickly.
- The domain enforces deeper, business-specific rules.
Benefits of Layered Validation
Section titled “Benefits of Layered Validation”- Faster feedback at the system edge.
- Stronger guarantees inside the domain.
- Clear separation of concerns.
- Easier testing and maintenance.
Common Mistakes
Section titled “Common Mistakes”- Skipping domain-level validation, assuming outer checks are enough.
- Duplicating validations unnecessarily between layers.
- Embedding heavy validation logic into controllers instead of cleanly separating concerns.
Infrastructure-level Validation in DomusJS
Section titled “Infrastructure-level Validation in DomusJS”DomusJS comes with Zod as the default schema validator, but it provides all the necessary interfaces and abstractions so you can easily integrate your preferred validation library (such as Joi, Yup, or custom solutions) without being locked in.
Additionally, @domusjs/security
provides helpers for:
- Password policies.
- Hashing.
- Secure comparisons.