// ...rest of the initial code omitted for simplicity. const { check, validationResult } = require('express-validator');
app.post('/user', [ // username must be an email check('username').isEmail(), // password must be at least 5 chars long check('password').isLength({ min: 5 }) ], (req, res) => { // Finds the validation errors in this request and wraps them in an object with handy functions const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(422).json({ errors: errors.array() }); }
All the rules of a path are written as middleware, which coupled tightly with the router. This pattern may be fine for simple use case, but will make the maintenance difficult for a complex project.
In this article, I am going to use one module validation.js file to hold validation rules etc. and present the function as a middleware.