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

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

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

我自己find了一个解决方法,但是我不知道我是不是在做一些不必要的事情。 这里是代码(数据通过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)? 如果不是有更好/更标准的方法来做我以上所做的事情吗? 一般来说,我对节点/expression都很陌生。 谢谢。

由于express-validatorexpress-validatorexpress中间件,所以可以使用equals()

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

为了在express-validator版本4中使用新的检查API实现这个目标,你需要创build一个自定义的validation器函数,以便能够访问请求,如下所示:

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