javascript – 如何验证Node.js和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)?如果不是有更好/更标准的方法来做我上面做的事情?我对节点/表达一般都很新.谢谢.

解决方法

由于express-validator是 validator.js快速中间件,你可以使用 equals()

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

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...