[[:oktatas:web:express:typescript_ervenyesseg|< TypeScript érvényesség]]
====== Express - TypeScript validálás express-validator-ral ======
* **Szerző:** Sallai András
* Copyright (c) 2024, Sallai András
* Licenc: [[https://creativecommons.org/licenses/by-sa/4.0/|CC Attribution-Share Alike 4.0 International]]
* Web: https://szit.hu
===== Függőség =====
Az érvényesség ellenőrzéséhez a joi csomagot fogjuk használni.
npm install express-validator
===== Érvényesség ellenőrzése =====
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 }
===== Használat =====
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);