Tom*_*mmy 3 javascript validation 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
}
};
Run Code Online (Sandbox Code Playgroud)
所以我的问题是:在express-validator中是否有一个本地方法来检查(email === email_confirm)?如果不是有更好/更标准的方法来做我上面做的事情?一般来说,我对节点/表达很新.谢谢.
要使用快速验证器版本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
});
Run Code Online (Sandbox Code Playgroud)
express-validator与validator.jsexpress的中间件一样,您可以使用:equals()
req.checkBody('email_confirm', 'mail does not match').equals(req.body.email);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3486 次 |
| 最近记录: |