简体   繁体   中英

Check if passwords are equal jQuery

I am trying to validate whether two entered passwords are the same or not. But I can't seem to get it working. No matter what values I enter in my input fields, the result is always "true". Can you see what I am doing wrong?

HTML:

<div class="form-group" id="password">
<input type="password" class="form-control" placeholder="Password" name="password">
</div>
<div class="form-group" id="repassword">
<input type="password" class="form-control" placeholder="Confirm Password" name="repassword">
</div>

jQuery:

    //Check if password is set
    $('input[name=password]').blur(function() {
        if($(this).val().length == 0){
            $('#password').addClass('has-error');
        } else {
            $('#password').addClass('has-success');
        }
    });
    //Check if repassword is set
    $('input[name=repassword]').blur(function() {
        if($(this).val().length == 0){
            $('#repassword').addClass('has-error');
        } else {
            $('#repassword').addClass('has-success');
        }
    });
    //Check if password and repassword are equal
    $('input[name=password]').blur(function() {
        if ($(this).attr('value') !== $('input[name=repassword]').attr('value')) {
            $('#password').addClass('has-error');
            $('#repassword').addClass('has-error');
        } else {
            $('#password').addClass('has-success');
            $('#repassword').addClass('has-success');
        }
    });

You should be using .val() to get the value of the textbox

You could simplify the whole thing to this:

$('input').blur(function() {
    var pass = $('input[name=password]').val();
    var repass = $('input[name=repassword]').val();
    if(($('input[name=password]').val().length == 0) || ($('input[name=repassword]').val().length == 0)){
        $('#password').addClass('has-error');
    }
    else if (pass != repass) {
        $('#password').addClass('has-error');
        $('#repassword').addClass('has-error');
    }
    else {
        $('#password').removeClass().addClass('has-success');
        $('#repassword').removeClass().addClass('has-success');
    }
});

DEMO

You could use $('input').blur(function() instead, that way it will trigger on all inputs

You're never removing any of the classes, you have to remove them to make it work, otherwise css specificity will only show the styles for the most specific class

It could all be written much simpler

$('input[name=password], input[name=repassword]').on('change', function () {
    var password   = $('input[name=password]'),
        repassword = $('input[name=repassword]'),
        both       = password.add(repassword).removeClass('has-success has-error');

    password.addClass(
        password.val().length > 0 ? 'has-success' : 'has-error' 
    );
    repassword.addClass(
        password.val().length > 0 ? 'has-success' : 'has-error'
    );

    if (password.val() != repassword.val()) {
        both.addClass('has-error');
    }
});

FIDDLE

Use domElem.value or $(domElem).val() to get the value of a form element:

WORKING JSFIDDLE DEMO

$('input').on('input',function() {
    var pass = $('input[name=password]'),
        reps = $('input[name=repassword]'),
        pass_cont = $('#password'),
        reps_cont = $('#repassword');
     !$(this).is( '[name=password]' ) || $(function() {
         pass_cont.addClass( pass.val().length === 0 ? 'has-error' : 'has-success' )
         .removeClass( pass.val().length === 0 ? 'has-success' : 'has-error' );
     })();
     !$(this).is( '[name=repassword]' ) || $(function() {
         reps_cont.addClass( reps.val() === pass.val() ? 'has-success' : 'has-error' )
         .removeClass( reps.val() === pass.val() ? 'has-error' : 'has-success' );
     })();
});

It should be $(this).val() , not $(this).attr('value') . And check both fields when either is blurred:

$('input').blur(function () {
    if ($('input[name=password]').val() != $('input[name=repassword]').val()) {
        $('#password').removeClass().addClass('has-error');
        $('#repassword').removeClass().addClass('has-error');
    } else {
        $('#password').removeClass().addClass('has-success');
        $('#repassword').removeClass().addClass('has-success');
    }
});

jsFiddle example

In addition to what the others have said about using val() to get the value of the element instead of attr('val') (which could be derived from the HTML), the example also didn't work because:

  • You need to remove the has-error and has-success class before adding one or the other
  • You are checking the value of the second password field onblur of the first one. It seems like you should compare the two in one event handler as in adeneo's answer.

A more general way, using classes and without re-finding jquery objects:

    $('.psw')               .on('keyup', checkPasses)
function checkPasses (e) {
    $ps1 = $(e.delegateTarget)
    $ps2 = $ps1.siblings('.psw')
    $pss = $ps1.add($ps2)
    if ( $ps1.val() == $ps2.val() ) {
        $pss.css('color', 'green')[0].setCustomValidity('')         
  } else {      
        $pss.css('color', 'red')[0].setCustomValidity('Passwords do not match')
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM