简体   繁体   English

检查密码是否相等 jQuery

[英]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: 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: 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 您应该使用.val()来获取文本框的值

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 DEMO

You could use $('input').blur(function() instead, that way it will trigger on all inputs 您可以使用$('input').blur(function() ,这样它将在所有输入上触发

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 你永远不会删除任何类,你必须删除它们才能使它工作,否则css特异性只会显示最具体的类的样式

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: 使用domElem.value$(domElem).val()来获取form元素的值:

WORKING JSFIDDLE DEMO 工作JSFIDDLE演示

$('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') . 它应该是$(this).val() ,而不是$(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 jsFiddle例子

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: 除了其他人所说的使用val()来获取元素的值而不是attr('val') (可以从HTML派生)之外,该示例也没有用,因为:

  • You need to remove the has-error and has-success class before adding one or the other 在添加一个或另一个之前,您需要删除has-errorhas-success
  • You are checking the value of the second password field onblur of the first one. 您正在检查第一个密码字段onblur的值。 It seems like you should compare the two in one event handler as in adeneo's answer. 看起来你应该像在adeneo的回答中那样比较二合一事件处理程序。

A more general way, using classes and without re-finding jquery objects:一种更通用的方法,使用类而不重新查找 jquery 对象:

    $('.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')
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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