Az érvényesség ellenőrzéséhez a joi csomagot fogjuk használni.
npm install express-validator
import { body, validationResult } from 'express-validator'; import { NextFunction, Request, Response } from 'express'; const empValidator = [ body('name').isString().isLength({ min: 2 }), body('city').isString().isLength({ min: 2 }).optional(), body('salary').isNumeric().optional(), (req: Request, res: Response, next: NextFunction) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } next(); } ]; export { empValidator }
import { Router } from 'express'; import EmployeeController from '../controllers/employeeController'; import { empValidator } from '../middlewares/validate'; const router = Router(); router.get('/employees', EmployeeController.index); router.post('/employees', empValidator, EmployeeController.store); export default router;
Ha szeretnél más köztes szoftvert is:
router.post('/employees', authorization, empValidator, EmployeeController.store);