Check Passwords Using jQuery

We have had several requests on how to use jQuery to check that passwords match in your website registration form when requesting visitors to re-enter their passwords.

This can easily be achieved by using similar code shown in our previous posts on Using jQuery to Validate Search Box Input and Email Validation Using jQuery.

1. The Password Input Fields

<form method="post" name="form1" id="form-password" action="">
    <input type="password" name="password" id="password" value="" size="32" />
    <label>Re-Enter Password:</label>
    <input type="password" name="password-check" id="password-check" value="" size="32" />
    <input type="submit" value="Submit" id="submit">

2. The jQuery Validation Code – Check That Both Passwords Match

        var hasError = false;
        var passwordVal = $("#password").val();
        var checkVal = $("#password-check").val();
        if (passwordVal == '') {
            $("#password").after('<span class="error">Please enter a password.</span>');
            hasError = true;
        } else if (checkVal == '') {
            $("#password-check").after('<span class="error">Please re-enter your password.</span>');
            hasError = true;
        } else if (passwordVal != checkVal ) {
            $("#password-check").after('<span class="error">Passwords do not match.</span>');
            hasError = true;
        if(hasError == true) {return false;}

The above code will perform the following checks upon clicking the submit button:

  • Check that a password has been entered and return an error message if the input field is empty.
  • Check that the “re-enter password” field contains text and return an error message if the input field is empty.
  • Finally – compare both password texts to check if they match

If any of the validation checks return an error then the form submission on your website is stopped with the “return false” command.

Check out the demo.


Leave a comment

To add code to your comments wrap the code text in [text][/text] tags