问题
I have a simple registration form as follows:
<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>
My register route looks like this:
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");
});
});
})
I need to throw an error if the password fields don't match to prevent user registration. I figured it might be best to write some middleware and insert it in the register route, but I've been playing around with code and cannot quite work out how to write this middleware. Can anybody help?
My thoughts are that this requires some kind of if statement along the lines of if(document.getElementById("password1").value != document.getElementById("password2").value then hijack the POST route, but not sure how to write it or where to insert it in the code?
Update: I still don't have a solution for this.
I've now tried the following in my JS file but it doesn't work either:
$('#submit-login').on('submit', function(e){
e.preventDefault();
if($('#password1').val() !== $('#password2').val());
alert("Passwords don't match!")
}
)
Anyone able to advise?
来源:https://stackoverflow.com/questions/43080130/how-to-prevent-registration-if-password-and-confirm-password-are-not-the-same