install the package:
npm i express-validator
In package.json, change to 5.3.1
re-install everything:
npm install
create validator folder. Then create index.js file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
exports.createPostValidator = (req, res, next) => { // title req.check('title', 'Write a title').notEmpty(); req.check('title', 'Title must be between 4 to 140 characters').isLength({ min: 4, max: 150 }); // body req.check('body', 'Write a Body').notEmpty(); req.check('body', 'Body must be between 4 to 2000 characters').isLength({ min: 4, max: 2000 }); // check for errors const errors = req.validationErrors() if (errors) { const firstError = errors.map(error => error.msg)[0]; return res.status(400).json({error: firstError}); } next(); } |