如果密码和确认密码不同,如何防止注册

时间:2017-03-28 21:17:38

标签: node.js passwords middleware

我有一个简单的注册表格如下:

<div class ="container form">

<div class="jumbotron form"><h2><i class="fa fa-user-plus" aria-hidden="true"></i> Signup</h2></div>
<form action = "/register" method="POST">
<div class="form-group">
    <i class="fa fa-user" aria-hidden="true"></i>
    <label for="username">Username</label>
        <input type = "text" class = "form-control" placeholder = "Enter username" name="username"> 
</div>
<div class="form-group">
    <i class="fa fa-key" aria-hidden="true"></i>
    <label for="password1">Password</label>
        <input id="password1" type = "password" class ="form-control" placeholder = "Enter password" name="password1">
</div>
<div class="form-group">
    <i class="fa fa-key" aria-hidden="true"></i>
    <label for="password2">Confirm password</label>
        <input id="password2" type = "password" class ="form-control" placeholder = "Enter password" name = "password">
</div>
<div class="form-group">
<i class="fa fa-picture-o" aria-hidden="true"></i>
    <label for="img">Image</label>
        <input type = "text" class ="form-control" placeholder = "Enter image URL" name = "image">
</div>
    <button id="submit-login" type ="submit" class="btn btn-primary btn-lg">Signup</button>
</form>
</div>

我的注册路线如下:

router.post("/register", function(req, res){
var newUser = new User({username: req.body.username, image: req.body.image});
User.register(newUser, req.body.password, function(err, user){
if(err){
    res.redirect("/blogs");
    console.log(err);
} 
passport.authenticate("local")(req, res, function(){
    res.redirect("/blogs");
});
});
})

如果密码字段不匹配以防止用户注册,我需要抛出错误。我认为最好编写一些中间件并将其插入寄存器路径,但我一直在玩代码,并且无法完全弄清楚如何编写这个中间件。有人可以帮忙吗?

我的想法是,这需要某种if语句if(document.getElementById(&#34; password1&#34;)。value!= document.getElementById(&#34; password2&#34;) .value然后劫持POST路由,但不知道如何写它或在代码中插入它的位置?

更新:我仍然没有解决方案。

我现在在我的JS文件中尝试过以下操作,但它不起作用:

$('#submit-login').on('submit', function(e){
e.preventDefault();
if($('#password1').val() !== $('#password2').val());
    alert("Passwords don't match!")
}
)

任何人都可以提供建议吗?

0 个答案:

没有答案