40

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!

Álvaro González
  • 128,942
  • 37
  • 233
  • 325
Igal
  • 4,662
  • 15
  • 57
  • 108
  • I think its logical error... KeyUp bind ur message on every keyup event i think better call function on focusout event – Sanjay Goswami Mar 15 '12 at 10:17
  • The invalid syntax infact is the problem. As told in the answer below either you can handle all of this in jquery as you are using it already, or just change the name of the events to onchange(onchange is fired only when the field loses focus, so as soon as you go to some other field or click outside you should get what you need) or use onkeyup as the event names instead of onChange and onKeyUp. – Alok Swain Mar 15 '12 at 10:17
  • 1
    @SanjayGoswami - The script does not get binded multiple times. These intrinsic events as described by w3c take a value that is a script and execute it when the event occurs for that element. – Alok Swain Mar 15 '12 at 10:22
  • I've edited your question to fix the first "does not work" (the most useless description you could use), but I have no idea about the second "does not work". Feel free to fix it yourself. – Álvaro González Mar 15 '12 at 10:22
  • Thank you all for your insights! I changed it now to the jquery handling, work great! I'm a beginner, reading and learning, so all of your suggestions are much appreciated! Again, thank you! – Igal Mar 15 '12 at 11:38
  • @Igal Question: are you displaying to the user whether or not their password is valid while they are typing? Security-wise this could be a flaw, as it would be possible to figure out someone else's password. – Skytiger Oct 01 '13 at 09:28

7 Answers7

54

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

musefan
  • 45,726
  • 20
  • 123
  • 171
  • 4
    +1 There's no point in loading jQuery and avoid using its event handling features. – Álvaro González Mar 15 '12 at 10:23
  • @musefan Thank you very much! Yes, it did solve this problem! – Igal Mar 15 '12 at 11:20
  • you have to check confirm pass value like this..if($(this).val() != $('#txtNewPassword').val().substr(0,$(this).val().length))..because if user typing password right then also for till end it display didnt match – sandeep Mar 15 '12 at 11:45
  • @sandeep: You don't have to use `$(this)` - if you see my JSFiddle example it works fine. Also, it is not recommended to use `this` when calling a standalone function, because if something else calls that function it won't work properly – musefan Mar 15 '12 at 12:22
  • Note: The fiddle example has a bug: If you type the password, then confirm it and then change the original password, it won't check the match. One should place the check call on both controls. – Balage1551 Aug 24 '16 at 08:47
  • @Balage1551: I wouldn't say that is a bug, I would say that is a different set of requirements. The OP was suggesting the check should be done in the confirm password box only, and if that is the design they want then it is correct to do so. If your requirements are different, then so be it, but it's not a bug. Personally I would probably agree with you that it is better to check on both, but it is merely preference rather than fact – musefan Aug 24 '16 at 09:23
11

Here's a working jsfiddle

http://jsfiddle.net/dbwMY/

Things to note:

  • validate event handler bound within the document.ready function - otherwise the inputs won't exist when the JS is loaded
  • using keyup

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.

reach4thelasers
  • 23,986
  • 21
  • 87
  • 119
6
$(function() {
    $("#txtConfirmPassword").keyup(function() {
        var password = $("#txtNewPassword").val();
        $("#divCheckPasswordMatch").html(password == $(this).val()
            ? "Passwords match."
            : "Passwords do not match!"
        );
    });
});​

Demo here

Salman A
  • 229,425
  • 77
  • 398
  • 489
4
$('#txtConfirmPassword').keyup(function(){


if($(this).val() != $('#txtNewPassword').val().substr(0,$(this).val().length))
{
 alert('confirm password not match');
}



});
sandeep
  • 2,196
  • 1
  • 23
  • 36
3

The problem in this case is that onchange-event does not fire until the input looses focus, so you will probably want to listen for the keyup-event instead, which is fired on every keystroke.

Also, I would prefer not using inline-javascript, but rather catch the event using jQuery instead.

$("#txtConfirmPassword").keyup(checkPasswordMatch);
Christofer Eliasson
  • 29,772
  • 6
  • 69
  • 99
1

if we use bootstrap our text will be green or red depending on the result

HTML

<div class="col-12 col-md-6 col-lg-4 mb-3">
            <label class="form-group d-block mb-0">
        <span class="text-secondary d-block font-weight-semibold mb-1">New Password</span>
<input type="password" id="txtNewPassword" class="form-control">     
        </label>
        </div>
        <div class="col-12 col-md-6 col-lg-4 mb-3">
            <label class="form-group d-block mb-0">
        <span class="text-secondary d-block font-weight-semibold mb-1">Confirm Password
        </span>
        <input class="form-control" type="password" id="txtConfirmPassword" onkeyup="checkPasswordMatch();">   
            </label>
        </div>
        <div class="registrationFormAlert" id="divCheckPasswordMatch"></div>

CSS

.text-success {
    color: #28a745;
}
.text-danger {
    color: #dc3545;
}

JS

function checkPasswordMatch() {
        var password = $("#txtNewPassword").val();
        var confirmPassword = $("#txtConfirmPassword").val();

        if (password != confirmPassword)
            $("#divCheckPasswordMatch").html("Passwords do not match!").addClass('text-danger').removeClass('text-success');

        else
            $("#divCheckPasswordMatch").html("Passwords match.").addClass('text-success').removeClass('text-danger');
    }
Adam Colton
  • 99
  • 1
  • 5
1

The onkeyup event does "work" as you intend:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head><title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript"><!--
function checkPasswordMatch() {
    var password = $("#txtNewPassword").val();
    var confirmPassword = $("#txtConfirmPassword").val();

    if (password != confirmPassword)
        $("#divCheckPasswordMatch").html("Passwords do not match!");
    else
        $("#divCheckPasswordMatch").html("Passwords match.");
}
//--></script>
</head>
<body>

<div class="td">
    <input type="password" id="txtNewPassword" />
</div>
<div class="td">
    <input type="password" id="txtConfirmPassword" onkeyup="checkPasswordMatch();" />
</div>
    <div class="registrationFormAlert" id="divCheckPasswordMatch">
</div>

</body>
</html>
Álvaro González
  • 128,942
  • 37
  • 233
  • 325
  • Hmmm, yes, it worked. I wonder how come it didn't work the first time I tried it... *scratchhead* Thank you! – Igal Mar 15 '12 at 11:22