express-validator: how to check queries

Valeri picture Valeri · Aug 20, 2018 · Viewed 9.3k times · Source

With express-validator how can we check the query for a request?

In the documentation there is an example to check body:

const { check, validationResult } = require('express-validator/check');

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() });
  }

  User.create({
    username: req.body.username,
    password: req.body.password
  }).then(user => res.json(user));
});

How can I set it to check only the query for GET methods?

GET /user?username=name I just want to check username in the query here.

Answer

user6184932 picture user6184932 · Jun 29, 2019

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