密码强度的jQuery表单验证

时间:2018-04-05 06:36:58

标签: jquery html

我对jquery验证有点困惑,在我的密码验证中,只有1个错误条件正在工作,如果我评论1个条件然后另一个1工作正常,但两个都不工作,意味着第一个一个不工作但第二个工作。如何使它们都具有不同的输出。

<script>
            //Password validation for blank and strong only
            jQuery("#password").blur(function() {
            var password = document.getElementById('fullname').value;

            checkStrength($('#password').val());
            });

            function checkStrength(password){
                //initial strength
                var strength = 0;

                //if the password length is 0, return message. 
                if (password.length == 0) { 
                    $('#pmessage').html('Password cannot be blank.').css('color', 'red');
                }
                else { 
                    $('#pmessage').html('');
                }

                //if the password length is less than 6, return message. 
                if ((password.length > 0) && (password.length < 6)) {
                    $('#pmessage').html('Too short.').css('color', 'red');
                }
                else { 
                    $('#pmessage').html('');
                }

            }
        </script>

2 个答案:

答案 0 :(得分:0)

您可以使用append代替html。见代码

<script>
    jQuery("#password").blur(function() {
        var password = document.getElementById('fullname').value;

        checkStrength($('#password').val());
    });

    function checkStrength(password){
        //initial strength
        var strength = 0;
        $('#pmessage').html('').css('color', 'red');
        //if the password length is 0, return message. 
        if (password.length == 0) {
            $('#pmessage').append('<div>Password cannot be blank.</div>');
        }

        //if the password length is less than 6, return message. 
        if ((password.length > 0) && (password.length < 6)) {
            $('#pmessage').append('<div>Too short.</div>');
        }
    }
</script>

答案 1 :(得分:0)

在第二种情况下检查password.length != 0

//Password validation for blank and strong only
jQuery("#password").blur(function() {
  checkStrength($('#password').val());
});

function checkStrength(password) {
  //initial strength
  var strength = 0;
  //if the password length is 0, return message. 
  if (password.length === 0) {
    $('#pmessage').html('Password cannot be blank.').css('color', 'red');
  } else {

    $('#pmessage').html('');
  }
  //if the password length is less than 6, return message. 
  if ((password.length > 0) && (password.length < 6)) {

    $('#pmessage').html('Too short.').css('color', 'red');
  } else {
    if (password.length != 0)
      $('#pmessage').html('');
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='password' />
<label id='pmessage'></label>