最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Check if passwords are equal jQuery - Stack Overflow

programmeradmin3浏览0评论

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');
        }
    });

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');
        }
    });
Share Improve this question asked Jul 8, 2014 at 20:49 madsobelmadsobel 3,2573 gold badges16 silver badges22 bronze badges 3
  • Is there a reason that the actions are being bound separately? – circusdei Commented Jul 8, 2014 at 20:51
  • 3 You're using val() so you know it exists, yet for some reason you suddenly decided to use attr('value'), why ? – adeneo Commented Jul 8, 2014 at 20:51
  • Please tell me you also have server code in place that also checks. Doing anything with passwords client side is scary. – asawyer Commented Jul 8, 2014 at 20:55
Add a comment  | 

6 Answers 6

Reset to default 7

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')
    }
}
发布评论

评论列表(0)

  1. 暂无评论