Apply Validation to User Routes
Update src/routes/user.routes.js.
Apply the create schema to the POST endpoint and the update schema to the PATCH endpoint.
PUT should use a separate schema that requires all editable replacement fields. We will use the same underlying field constraints but require the fields explicitly.
PUT and PATCH Validation
PUT should require a complete editable representation. PATCH should allow a subset of editable fields. Do not use an optional-only schema for both operations.
Validated User Routes
import { Router } from 'express';
import { validateBody } from '../middleware/validate.middleware.js';
import {
createUserSchema,
updateUserSchema,
replaceUserSchema
} from '../validators/user.validator.js';
import {
createUser,
getAllUsers,
getUserById,
updateUser,
deleteUser
} from '../controllers/user.controller.js';
const router = Router();
router.post('/', validateBody(createUserSchema), createUser);
router.get('/', getAllUsers);
router.get('/:id', getUserById);
router.put('/:id', validateBody(replaceUserSchema), updateUser);
router.patch('/:id', validateBody(updateUserSchema), updateUser);
router.delete('/:id', deleteUser);
export default router;Applies validation middleware before controllers. replaceUserSchema must be defined in the validator module with all required editable fields.
Key Takeaways
Apply validation at the route level.
Validate before executing controller logic.
Keep PUT and PATCH semantics separate.