我第一次使用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);