繁体   English   中英

表达验证器自定义错误不起作用

[英]express validator custom error not working

我正在使用 express-validator 来验证输入,还使用 Sequelize ORM 进行数据库查询。 尝试在 express-validator 上验证自定义 function。 function 总是失败,无论 output 这是验证器主体

验证器:

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.'),

这就是我从 controller 发送结果的方式:

const errors = validationResult(req);
 if (!errors.isEmpty()) {
 return res.status(422).json({ errors: errors.array() });
}

Sequelize 工作正常,但验证总是失败。 我尝试返回 boolean 但这些也失败了。

console.log errors.array()并查看这些故障是什么并修复它们。

if (!errors.isEmpty()) {
 console.log(errors.array());
 return res.status(422).json({ errors: errors.array() });
}

    

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM