【发布时间】:2017-08-10 06:55:04
【问题描述】:
我第一次使用 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)?如果没有,是否有更好/更标准的方法来做我上面所做的事情?一般来说,我对 node/express 很陌生。谢谢。
【问题讨论】:
-
表单验证可以在发送请求之前在客户端javascript本身上完成。
-
@BharathvajGanesan 感谢您的评论。我考虑过在客户端验证电子邮件是否相等,但由于我已经在服务器端使用 express-validator 进行验证,所以我只想将它们放在一起。
-
K 很好 @Tommy... 还有其他用于 express 的表单验证器试试这个灵活的 [www.npmjs.com/package/express-form-handler] 它类似于 jquery form-validator,你可以编写自己的规则和策略
标签: javascript node.js validation express