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!
It is the simple method to verify the password matches. First password is stored into a password1 variable and confirm password is stored in password2 variable. Then check if both variable value is equal then password match otherwise password does not match.
To check confirm password field in form without reloading page with JavaScript, we can check the input values. to add the password inputs. const check = () => { if ( document. getElementById("password").
If users mistype their password, they won't recognize it. The confirm password catches typos by prompting users to type their password twice.
This can be done by document. getElementById() function, which selects an element by its id. var text1 = document. getElementById("username");
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With