我使用express-validator customValidators添加一些特定的验证器:
middlewares.js
module.exports = function (app) {
console.log('to be sure that Im called');
return function (request, response, next) {
app.use(expressValidator({
customValidators: {
checkObjectId: function(name) {
return /^[0-9a-fA-F]{24}$/.test(name);
}
}
}));
next();
}
};
route.js
const middleware = require(__path + '/middlewares');
module.exports = function (app, passport) {
router.use(baseUrl, middleware(app));
// some codes
router.put(baseUrl + '/invoice/:invoiceId', api.invoices.invoices.update);
}
invoices.js
update: (request, response) => {
// some codes
request.checkBody('from', 'invalid Supplier Id').checkObjectId();
// some codes
},
我的问题是无法识别checkObjectId,我有这个错误:
TypeError: request.checkBody(...).checkObjectId is not a function
答案 0 :(得分:1)
您正在导出一个导出声明中间件的中间件的函数。
这应该足够了:
// middlewares.js
module.exports = expressValidator({
customValidators: {
checkObjectId: function(name) {
return /^[0-9a-fA-F]{24}$/.test(name);
}
}
});
使用:
const middleware = require(__path + '/middlewares');
module.exports = function (app, passport) {
router.use(baseUrl, middleware);
...
}
如果你真的想要导出一个函数 - 返回一个中间件,你可以使用它:
module.exports = function(app) {
return expressValidator({
customValidators: {
checkObjectId: function(name) {
return /^[0-9a-fA-F]{24}$/.test(name);
}
}
})
};