Note: I originally wrote this blog post in March of 2012. For the most part, this is the same content, though I have updated and expanded it a bit. In modern times, we use a CMS or some sort of framework that has a built-in password validation. However, there are still plenty of occasions where you’ll build a registration or password reset page where you need to check that the user has entered the correct password prior to submitting the page. This simple Javascript Tutorial will show you how to do just that.
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.
We’ll look at validating the password using vanilla JavaScript and also doing it with jQuery.
Vanilla Javascript (no framework used)
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:
As you can see, the Javascript is short and simple. It follows the plan of what we wanted to do and, even with comments, it’s only 28 lines long.
Now let’s look at doing the same thing with jQuery.
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.