Checking password match while typing
I have a registration form with "password" and "confirm password" input fields. I want to check if the "confirm password" matches the "password" while the user is typing it and give the appropriate message. So I tried to do this:
This is the HTML:
<div class="td">
<input type="password" id="txtNewPassword" />
</div>
<div class="td">
<input type="password" id="txtConfirmPassword" onChange="checkPasswordMatch();" />
</div>
<div class="registrationFormAlert" id="divCheckPasswordMatch">
</div>
And this is the checkPasswordMatch() function:
function checkPasswordMatch() {
var password = $("#txtNewPassword").val();
var confirmPassword = $("#txtConfirmPassword").val();
if (password != confirmPassword)
$("#divCheckPasswordMatch").html("Passwords do not match!");
else
$("#divCheckPasswordMatch").html("Passwords match.");
}
That didn't validate while typing, only when user leaves the field.
I tried to use onKeyUp instead of onChange - also didn't work.
So how can it be done?
Thank you!
Probably invalid syntax in your onChange event, I avoid using like this (within the html) as I think it is messy and it is hard enough keeping JavaScript tidy at the best of times.
I would rather register the event on the document ready event in javascript. You will also definitely want to use keyup event too if you want the validation as the user is typing:
$(document).ready(function () {
$("#txtConfirmPassword").keyup(checkPasswordMatch);
});
Here is a working example
Personally I would prefer to do the check when either password field changes, that way if they re-type the original password then you still get the same validation check:
$(document).ready(function () {
$("#txtNewPassword, #txtConfirmPassword").keyup(checkPasswordMatch);
});
Here is a working example
Here's a working jsfiddle
http://jsfiddle.net/dbwMY/
Things to note:
- validate event handler bound within the document.ready function - otherwise the inputs won't exist when the JS is loaded
- using keyup
In saying that, validation is a solved problem there are frameworks that implement this functionality.
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
I'd suggest using one of these rather than reimplementing Validation for every app you write.
$(function() {
$("#txtConfirmPassword").keyup(function() {
var password = $("#txtNewPassword").val();
$("#divCheckPasswordMatch").html(password == $(this).val()
? "Passwords match."
: "Passwords do not match!"
);
});
});
Demo here