我正在使用 npm 模块[express-validator][1]
来验证我的query
和body
参数。在 express 中,我们可以将函数列表作为中间件传递,我创建了一个单独的文件作为验证器。这是我的验证器代码..
creditcard.validator.js
const { check, body , query ,oneOf, validationResult } = require('express-validator/check');
exports.post_credit_check = [
function(req,res,next) {
body('firstName')
.exists()
.isAlphanumeric().withMessage('firstName should be alpanumeric')
.isLength({min: 1 , max: 50}).withMessage('firstName should not be empty, should be more than one and less than 50 character')
.trim();
var errorValidation = validationResult(req);
if ( errorValidation ) {
return res.status(500).json({
title: 'an error occured',
error: errorValidation
});
}
next()
},
function(req,res,next) {
body('lastName')
.exists()
.isAlphanumeric().withMessage('lastName should be alpanumeric')
.isLength({min: 1 , max: 50}).withMessage('lastName should not be empty, should be more than one and less than 50 character')
.trim();
var errorValidation = validationResult(req);
if ( errorValidation ) {
return res.status(500).json({
title: 'an error occured',
error: errorValidation
});
}
next()
}
];
这route
是我传递中间件验证器数组的文件
var express = require('express');
var router = express.Router();
var Creditcard = require('../models/creditcard.model');
const { validationResult } = require('express-validator/check');
var validate = require('../models/creditcard.validate');
router.post('/creditcarddetails', validate.post_credit_check , function(req, res, next) {
.................
}
尽管我将所有中间件函数传入validate.post_credit_check
,但它没有验证主体并且没有给出错误。