我使用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
最佳答案
您正在导出一个函数,该函数导出一个声明中间件的中间件。
这应该足够了:
// 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);
}
}
})
};
关于javascript - NodeJs Express-Validator customvalidators不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44177514/