如何使用自定义快速验证器?

时间:2018-02-19 23:35:48

标签: javascript node.js express express-validator

我正在开发一个注册表单,我正在使用express-validator来验证字段,但如果电子邮件已经存在,我在验证方面遇到了麻烦。

我做了一个选择来检查插入的电子邮件是否已经存在,但它总是返回我的电子邮件。

我尝试了其他方法,但没有奏效。

这是我的post request

routes.post('/register', function(req,res)
{
    var email = req.body.email;
    var username = req.body.username;
    var password = req.body.password;
    var password2 = req.body.password2;

    // Validation
    req.checkBody('email', 'Email is required').notEmpty();
    req.checkBody('email', 'Email is not valid').isEmail();
  req.checkBody('email', 'Email already exists').custom(value => {
    return User.findUserByEmail(value).then(function(user) {
      throw new Error('this email is already in use');
    })
  });

    req.checkBody('username', 'Username is required').notEmpty();
    req.checkBody('password', 'Password is required').notEmpty();
    req.checkBody('password2', 'Passwords do not match').equals(req.body.password);

    var errors = req.validationErrors();

    if(errors){
    console.log(errors);
        res.render('register',{
            errors:errors
        });
    } else {
    console.log("passed");

        var newUser = {
            email:email,
            username: username,
            password: password
        };


        User.createUser(newUser, function(err, User){
            if(err) throw err;
            console.log(User);
        });

        req.flash('success_msg', 'You are registered and can now login');

        res.redirect('/login');
    }
});

我的功能findUserByEmail

module.exports.findUserByEmail = function(email, callback){
  var connection = db.setDB('DB1');
  connection.then(result => {
    var request = new mssql.Request(conn);
    console.log("SELECT * FROM u_users WHERE email = '"+email+"'");
    var exists = request.query("SELECT * FROM u_users WHERE email = '"+email+"'");

    Promise.all([exists]).then(function(results)
    {

      console.log(results);
      if(results[0].length == 0)
      {
        console.log("1");
        return false;
      }
      console.log("2");
      return true;
    }).catch(function(err)
    {
      console.log("Error verifying email...");
      console.log(err);
    });
  });
}

如果我这样做,则会返回错误Cannot read property 'then' of undefined

我做错了什么?

1 个答案:

答案 0 :(得分:0)

关于错误Cannot read property 'then' of undefined.,这是因为您未从findUserByEmail函数返回承诺。

除此之外,如果保持原样,您的自定义验证器将始终失败。

您的findUserByEmail仅返回true / false,这意味着"使用此值"来解决此承诺。 您可能想要更改它以返回找到的用户(并且还使其名称显示其真正的作用!):

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;
    });
}

现在,您需要检查自定义验证程序是否从该函数返回任何用户:

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');
        }
    })
});

你已经完成了!