上述解决方案有效,但它们存在一个用于验证正文、查询或参数的快速库。
您可以按照以下步骤操作。
1)。首先通过这个命令安装库。
npm install --save express-validator
2)。现在你的路线被定义了,导入这个
const { body, query, param } = require("express-validator");
3)。现在在您的路线中,您可以使用上述任一对象示例..
router.post('/upload',
[
query('id')
.not()
.isEmpty()
.withMessage('id field can not be empty')
.matches(/^[0-9]+$/)
.withMessage('id must be integer only'),
body('fullName')
.trim()
.not()
.isEmpty()
.withMessage('fullName can not be empty')
.matches(/^[A-Za-z]+$/)
.withMessage('fullName must be Alpha only')
],
userController.fetchProperty
);
它们是在包中定义的方法数量,因为我在上面的示例中使用了其中一些方法,例如 isEmpty()、matches()、isInt() 等。
4)。现在在定义逻辑的控制器中,您首先需要导入它
const { validationResult } = require("express-validator");
5)。现在在你的逻辑中,你只需要通过传递 req, res 对象来调用这个函数
const checkInputError = (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
res.status(422).json({
message: 'failure',
status: 422,
errors: errors.array()
});
}
};
现在,您将在正文、查询或参数中应用整个验证错误作为响应。
希望这会对您或其他人有所帮助!
更多查询可以参考这里。
https://express-validator.github.io/docs/