Express-Validator:验证错误消息不出现在自定义验证器上

时间:2017-11-13 18:14:26

标签: node.js express express-validator

如果我尝试注册重复的用户名,则一切正常,但错误消息表明它已经注册。所有其他错误消息都有效;不是这个。

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

req.checkBody('name', 'Name is required').notEmpty();
req.checkBody('name', 'This name is already registered.')
.custom(function(name, req){
    return new Promise((resolve, reject) => {
        User.findOne({ name: name }, (err, user) => {
            console.log(name);
            console.log(user);
            if (err) throw err;
            if(user == null) {
                resolve();
            } else {
                console.log('rejecting');
                reject();
            }
        });
    });
}); 

req.checkBody('email', 'Email is required').notEmpty();
req.checkBody('email', 'Email is not valid').isEmail();
// 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){
    res.render('register',{
        errors:errors
    });
} else {
    var newUser = new User({
        name: name,

我错过了什么?

1 个答案:

答案 0 :(得分:0)

我很确定您在代码中链接custom()的方式仅适用于新API。您正在使用旧版API。对于遗留API,您必须在应用中间件时定义自定义验证器(在app.js或类似的东西中)。例如:

app.use(expressValidator({
  customValidators: {
    isUniqueName: function(name) {
      return new Promise((resolve, reject) => {
        User.findOne({ name: name }, (err, user) => {
          console.log(name);
          console.log(user);
          if (err) throw err;
          if (user == null) {
            resolve();
          } else {
            console.log('rejecting');
            reject();
          }
        });
      });
    },
  },
}));

并在控制器中:

req.checkBody('name', 'This name is already registered.').isUniqueName();

我通常建议您更改为新的API。当您已经知道要验证的内容时,不应该花费太多时间。它更多地写了here