express-validator自定义validator的custom()

徐瀚
2023-12-01

使用express-validator进行邮箱(用户名/...)存在性验证时,自定义custom时出了很多问题,遇到的问题有:

  • cannot read property xx
  • invalid value
  • 总是无法通过check,提示错误信息,无论你填的是否正确

点击链接查看express-validator documentation中的详细解释

简单来说custom(validator())的validator函数必须要返回一个Promise.reject(msg)或者throw new Error(msg)

如果通过检查必须返回一个值(随意指定,譬如1,或者返回validator的参数value)

 

validator的实质就是一个原生promise,必须实现resolve和reject. 官方api文档的例子有误,通过检查没返回值,

还有个情况,我用的mongoose的Model.find()它不是full-fledged的promise,

mongoose关于promise接口的解释

文档中说.then()不是full-fledged而exec是full-fledged但经过我测试.exec()依然不可以,我将Model.find()手动改写成

原生promise后成功了

贴一条express-validator作者的示例代码

//./models/users.js
module.exports.findUserByEmail = function(email, callback){

    var request = new mssql.Request(conn);
    console.log("SELECT * FROM u_users WHERE email = '"+email+"'");
    var query = request.query("SELECT * FROM u_users WHERE email = '"+email+"'");

    return query.then(function(results) {
      return results[0];
    }).catch(function(err) {
      console.log("Error verifying email...");
      console.log(err);
      throw err;
    });
}
// ./routes/users.js
req.checkBody('email', 'Email already exists').custom(value => {
    return User.findUserByEmail(value).then(function(user) {
        if (user) {
            throw new Error('this email is already in use');
        }
    })
});

贴一条自己写的代码

check('username').trim().custom(value=>{
                return new Promise((resolve,reject) => {
                    User.findOne({username:value},(err,res) => {
                        if (err) reject(err)
                        if (res) reject('username already exists')
                        resolve('ok')
                    })
                })
        })



check('password2').trim().custom((value,{req})=>{
            if(value!==req.body.password){
                throw new Error('Password does not match')
            } 
            return 1
        })

 

 类似资料: