Here is how to validate query parameters using express validator.
To check for variables in query params, i.e., req.query, use query([fields, message]). Same as check([fields, message]), but only checking req.query.
Example:
Installing express-validator
npm install --save express-validator
Importing query
const { query } = require('express-validator/check');
Using query
router.post('/add-product',
isAuth,
[
query('title')
.isString().withMessage('Only letters and digits allowed in title.')
.trim()
.isLength({min: 3}).withMessage('Title too short. Enter a longer title!'),
query('price', 'Enter a valid price.')
.isFloat(),
query('description')
.trim()
.isLength({min: 30, max: 600}).withMessage('Description must be of minimum 30 and maximum 600 characters!'),
],
adminController.postAddProduct);
See official documentation here: https://express-validator.github.io/docs/check-api.html
Comments
Post a Comment