问题描述
我正在使用express-validator来验证输入,还使用Sequelize ORM进行数据库查询。尝试在express-validator上验证自定义函数。无论输出如何,该功能始终会失败这是验证器主体
验证者:
body('firmName').notEmpty().withMessage('Firm Name is required.').custom((name,{ req,loc,path }) => {
Firm.findOne({ where: { firmName: name }}).then(firm => {
if(firm != null) {
return Promise.reject('errr')
} else {
return Promise.resolve('Ok')
}
}).catch(err => {
console.log(err)
return Promise.reject('errr')
})
}).withMessage('Firm Name already exists.'),
这是我从控制器发送结果的方式:
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
Sequelize工作正常,但验证始终失败。我尝试返回布尔值,但是这些也失败了。
解决方法
console.log errors.array() ,查看这些故障是什么并进行修复。
if (!errors.isEmpty()) {
console.log(errors.array());
return res.status(422).json({ errors: errors.array() });
}