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:
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:
Here is a working example