Let’s start by looking at what our script will need to do.
Steps to Password Validation
Get The Input Elements
The first step will be to grab the input elements and store them into variables. This will allow us to work with the inputs throughout the script.
Capturing The Event
We want to check the values of the inputs every time someone releases a key in one of the input boxes. Once we’ve captured the event, we can compare the values of the two input boxes and ensure that they match.
Update the UI
Lastly, we want to give the user visual indication of whether the passwords match.
Using the onkeyup event, we can check what the user has entered in both fields and confirm that they have typed the same thing twice and visually confirm to the user that there is no problem with his password.
Here is a simple example:
Here is the code for that example:
Now let’s look at doing the same thing with jQuery.
The principle is the same, and it will function just like the one above, but the code looks a lot different:
You can see that we wrap the script in the jQuery document.ready function (using the shorthand version) and rather than putting a keyup event in the HTML form, we tell jQuery to watch for the keyup event.
I like this approach better because it separates all of the logic from the HTML. If you ever want to change which inputs are checked or remove the validation completely, you only have one place to edit.
Extending the Script
There’s a lot that you could do to extend the functionality of this simple script.
Changing the colors is a great visual identifier for the user, but for added security, the script could be extended to disable the form submit button or alert the user before they submit the form if the passwords do not match. The script and form could also be changed to use images for the confirmation rather than text. For example:
Overall, this is a very simple way to give the user feedback that their passwords match. However, you should still be doing server-side validation to make sure the password and confirm do, indeed, match.
I hope you found this bit of information useful … go forth and code.