快速验证器:如何检查查询

时间:2018-08-20 06:00:33

标签: node.js express express-validator

使用express-validator,我们如何检查查询中的请求?

文档中有一个检查正文的示例:

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

如何设置它仅检查GET方法的查询?

GET /user?username=name 我只想在此处的查询中检查username

3 个答案:

答案 0 :(得分:1)

验证者为-

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

const fetchStatementValidator = [
    check('startdate').not().isEmpty().withMessage("Start date cannot be empty"),
    check('enddate').not().isEmpty().withMessage("End Date cannot be empty"),
]

module.exports.fetchStatementValidator = fetchStatementValidator;

Api是-

router.get("/fetchStatement", auth.adminAuth, validator.fetchStatementValidator, utility.statements.fetchStatement); //fetch statement

API定义-

/* Fetch transections */
module.exports.fetchStatement = async (req, res, next) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        return res.status(422).json({
            success: false,
            errors: errors.array()
        });
    }
};

Api通过邮递员命中-

http://localhost:5000/loans/fetchCompletedLoans?page=1&startdate=2019-09-08&enddate=

响应-

{
    "success": false,
    "errors": [
        {
            "value": "",
            "msg": "End Date cannot be empty",
            "param": "enddate",
            "location": "query"
        }
    ]
}

答案 1 :(得分:0)

您可以通过以下方式实现此目标:

filter

答案 2 :(得分:0)

要检查查询参数中的变量,即req.query,请使用 query([fields,message])。 与检查([字段,消息])相同,但仅检查需求查询

示例:

安装快速验证器

npm install --save express-validator

导入查询

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

使用查询

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

在此处查看官方文档:https://express-validator.github.io/docs/check-api.html