如何验证Node.js和Express中应该相等的两个字段?

时间:2017-08-10 06:55:05

标签: javascript node.js validation express

我第一次使用express-validator,如果两个字段相等,我就找不到断言的方法(如果可以完成的话)。

示例:提交包含2次电子邮件地址(一个作为标准确认)的表单。我想检查字段是否匹配。

我发现自己的解决方法有效,但我想知道我是不是只做了不必要的事情。这是代码(数据来自ajax调用):

//routes.js

function validator(req, res, next) {

  req.checkBody('name', 'cannot be empty').notEmpty();
  req.checkBody('email', 'not valid email').isEmail();

  var errors = req.validationErrors(); // up to here standard express-validator

  // Custom check to see if confirmation email matches.

  if (!errors) errors = [];
  if (email !== email_confirm){
    errors.push({param: 'email_confirm', msg: 'mail does not match!', value: email_confirm})
  }

  if (errors.length > 0) {
    res.json({msg: 'validation', errors:errors}); // send back the errors
  }
  else {
    // I don't want to insert the email twice in the DB
    delete req.body.email_confirm
    next(); // this will proceed to the post request that inserts data in the db
  }
};

所以我的问题是:在express-validator中是否有一个本地方法来检查(email === email_confirm)?如果不是有更好/更标准的方法来做我上面做的事情?一般来说,我对节点/表达很陌生。谢谢。

2 个答案:

答案 0 :(得分:6)

要使用快速验证程序版本4中的新检查API实现此目标,您需要创建自定义验证程序函数才能访问请求,如下所示:

router.post(
    "/submit",
    [
    // Check validity
    check("password", "invalid password")
        .isLength({ min: 4 })
        .custom((value,{req, loc, path}) => {
            if (value !== req.body.confirmPassword) {
                // trow error if passwords do not match
                throw new Error("Passwords don't match");
            } else {
                return value;
            }
        })
    ],
    (req, res, next) => {
        // return validation results
        const errors = validationResult(req);

        // do stuff
    });

答案 1 :(得分:1)

由于express-validator是[{3}}的express中间件,您可以使用validator.js

req.checkBody('email_confirm', 'mail does not match').equals(req.body.email);
相关问题