Overview
PyqDeck implements a robust validation layer using Zod. Validation happens at two levels:- Schema Level: Defining the shape and constraints of data within our models.
- Middleware Level: Intercepting requests and validating
req.body,req.query, orreq.paramsbefore they reach the controller.
Zod Schemas in Models
Every Mongoose model has a corresponding Zod schema exported from the same file (e.g.,backend/src/models/University.js).
- Type Safety: Clearer documentation of what fields are required and their types.
- Reusability: The same schema can be used for both
POST(creation) andPATCH(updates, via.partial()).
Validation Middleware
ThevalidationMiddleware.js is a higher-order function that generates Express middleware for a given Zod schema.
Usage in Routes
How it Works
- Validation: It runs
schema.safeParse()againstreq.body. - Success: If valid, it replaces
req.bodywith the parsed (and potentially transformed/sanitized) data and callsnext(). - Failure: If invalid, it formats the Zod error into a human-readable message and throws a
ValidationError(400), which is then handled by the global error handler.
Validation Strategies
- Strict Mode: We generally allow extra fields in the request body but ignore them (Zod’s default behavior).
- Partial Updates: For
PATCHrequests, we useschema.partial()to make all fields optional while still enforcing types and constraints for the fields that are provided. - Query Validation: We also use Zod to validate pagination parameters (
page,limit,sort) in thepaginationMiddleware.

