如何在不重新加载页面的情况下检查表单中的确认密码字段

76

我有一个项目,需要添加一个注册表单。我希望能够在不点击注册按钮的情况下验证密码和确认密码是否相同。

如果密码和确认密码字段不匹配,则我还想在确认密码字段旁边放置一个错误消息并禁用注册按钮。

以下是我的HTML代码...

<form id="form" name="form" method="post" action="registration.php"> 
    <label >username : 
<input name="username" id="username" type="text" /></label> <br>
    <label >password : 
<input name="password" id="password" type="password" /></label>     
    <label>confirm password:
<input type="password" name="confirm_password" id="confirm_password" />
    </label>
<label>
  <input type="submit" name="submit"  value="registration"  />
</label>

有没有任何方法可以做到这一点?


可能是HTML-更改\更新页面内容而不刷新\重新加载页面的重复问题。 - Amal Murali
1
有很多种方法,你尝试了哪一种? - A. Wolff
15个回答

124

我们将探讨两种方法来实现这一点。使用jQuery和不使用jQuery。

1. 使用jQuery

您需要向密码和确认密码字段都添加keyup函数。原因是即使password字段更改,也应检查文本的相等性。感谢 @kdjernigan 指出这一点。

以这种方式,当您在字段中键入时,您将知道密码是否相同:

$('#password, #confirm_password').on('keyup', function () {
  if ($('#password').val() == $('#confirm_password').val()) {
    $('#message').html('Matching').css('color', 'green');
  } else 
    $('#message').html('Not Matching').css('color', 'red');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>password :
  <input name="password" id="password" type="password" />
</label>
<br>
<label>confirm password:
  <input type="password" name="confirm_password" id="confirm_password" />
  <span id='message'></span>
</label>

这里有一个示例: http://jsfiddle.net/aelor/F6sEv/325/

2. 不使用jQuery

我们将在两个字段上使用javascript的onkeyup事件来实现相同的效果。

var check = function() {
  if (document.getElementById('password').value ==
    document.getElementById('confirm_password').value) {
    document.getElementById('message').style.color = 'green';
    document.getElementById('message').innerHTML = 'matching';
  } else {
    document.getElementById('message').style.color = 'red';
    document.getElementById('message').innerHTML = 'not matching';
  }
}
<label>password :
  <input name="password" id="password" type="password" onkeyup='check();' />
</label>
<br>
<label>confirm password:
  <input type="password" name="confirm_password" id="confirm_password"  onkeyup='check();' /> 
  <span id='message'></span>
</label>

这是fiddle的链接:http://jsfiddle.net/aelor/F6sEv/324/


1
$('#password, #confirm_password').on('keyup', function () { if ($('#password').val() == $('#confirm_password').val()) { $('#message').html('匹配').css('color', 'green'); } else $('#message').html('不匹配').css('color', 'red'); }); 是同一段代码的另一个修改版本,它在每个密码输入框被修改时执行检查。这有助于如果他们输入了匹配的密码,然后意外修改了密码字段或更改了密码字段,它将更新匹配状态。http://jsfiddle.net/C3rMw/ - kdjernigan
1
@PhpBeginner:这是基本的Javascript..它没有使用任何JS库 :) - Abhishek Ghosh
@aelor:不确定其他人是否遇到了同样的问题。我输入密码,然后输入“确认密码”的数据——立即显示“密码匹配”,但当我完成输入“确认密码”详细信息时,“密码不匹配”会显示。即使我输入正确的确认密码或不正确的,仍然会始终显示“密码不匹配”的消息。这是我第一次进行UI开发。希望大家如果我有任何错误,请纠正我 :) - user2014
@user2014,您的 ready 函数应该包含 $("#password, #confirm_password").keyup(checkPasswordMatch); https://jsfiddle.net/aelor/00azu88j/1/。我在我的回答中也提供了原因。keyup 应该双向工作。这样,如果密码字段发生更改,则也会进行检查。 - aelor
感谢@aelor清晰的解释。不幸的是,现在我也一直看到“密码不匹配”的提示。 - user2014
显示剩余9条评论

31

使用本地setCustomValidity

在密码/确认密码输入值的change事件中比较它们的值,并相应地setCustomValidity

function onChange() {
  const password = document.querySelector('input[name=password]');
  const confirm = document.querySelector('input[name=confirm]');
  if (confirm.value === password.value) {
    confirm.setCustomValidity('');
  } else {
    confirm.setCustomValidity('Passwords do not match');
  }
}
<form>
  <label>Password: <input name="password" type="password" onChange="onChange()" /> </label><br />
  <label>Confirm : <input name="confirm"  type="password" onChange="onChange()" /> </label><br />
  <input type="submit" />
</form>


4
这是最高效、简单、棒极了和最好的方法。 - Ahmed Ali

19

如果您不想使用jQuery:

function check_pass() {
    if (document.getElementById('password').value ==
            document.getElementById('confirm_password').value) {
        document.getElementById('submit').disabled = false;
    } else {
        document.getElementById('submit').disabled = true;
    }
}
<input type="password" name="password" id="password" onchange='check_pass();'/>
<input type="password" name="confirm_password" id="confirm_password" onchange='check_pass();'/>
<input type="submit" name="submit"  value="registration"  id="submit" disabled/>

5

使用jQuery解决方案

 <script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>

 <style>
    #form label{float:left; width:140px;}
    #error_msg{color:red; font-weight:bold;}
 </style>

 <script>
    $(document).ready(function(){
        var $submitBtn = $("#form input[type='submit']");
        var $passwordBox = $("#password");
        var $confirmBox = $("#confirm_password");
        var $errorMsg =  $('<span id="error_msg">Passwords do not match.</span>');

        // This is incase the user hits refresh - some browsers will maintain the disabled state of the button.
        $submitBtn.removeAttr("disabled");

        function checkMatchingPasswords(){
            if($confirmBox.val() != "" && $passwordBox.val != ""){
                if( $confirmBox.val() != $passwordBox.val() ){
                    $submitBtn.attr("disabled", "disabled");
                    $errorMsg.insertAfter($confirmBox);
                }
            }
        }

        function resetPasswordError(){
            $submitBtn.removeAttr("disabled");
            var $errorCont = $("#error_msg");
            if($errorCont.length > 0){
                $errorCont.remove();
            }  
        }


        $("#confirm_password, #password")
             .on("keydown", function(e){
                /* only check when the tab or enter keys are pressed
                 * to prevent the method from being called needlessly  */
                if(e.keyCode == 13 || e.keyCode == 9) {
                    checkMatchingPasswords();
                }
             })
             .on("blur", function(){                    
                // also check when the element looses focus (clicks somewhere else)
                checkMatchingPasswords();
            })
            .on("focus", function(){
                // reset the error message when they go to make a change
                resetPasswordError();
            })

    });
  </script>

并相应地更新您的表单:

<form id="form" name="form" method="post" action="registration.php"> 
    <label for="username">Username : </label>
    <input name="username" id="username" type="text" /></label><br/>

    <label for="password">Password :</label> 
    <input name="password" id="password" type="password" /><br/>

    <label for="confirm_password">Confirm Password:</label>
    <input type="password" name="confirm_password" id="confirm_password" /><br/>

    <input type="submit" name="submit"  value="registration"  />
</form>

这将会精确地按照您的要求执行以下操作:

  • 验证密码和确认密码字段无需点击注册按钮即可相等
  • 如果密码和确认密码字段不匹配,则会在确认密码字段旁边放置错误消息并禁用注册按钮

建议不要为每个按键都使用keyup事件监听器,因为实际上您只需要在用户输入信息完成后对其进行评估。如果有人在速度较慢的机器上快速输入,他们可能会感到延迟,因为每个按键都会触发该函数。

此外,在您的表单中,您错误地使用了标签。label元素具有“for”属性,应与表单元素的id对应。这样,当视障人士使用屏幕阅读器调用表单字段时,它就会知道文本属于哪个字段。


你能加一些缩进并解释这个答案需要使用jQuery吗? - SparK

3
function check() {
    if(document.getElementById('password').value ===
            document.getElementById('confirm_password').value) {
        document.getElementById('message').innerHTML = "match";
    } else {
        document.getElementById('message').innerHTML = "no match";
    }
}

<label>password :
<input name="password" id="password" type="password" />
</label>
<label>confirm password:
<input type="password" name="confirm_password" id="confirm_password" onchange="check()"/> 
<span id='message'></span>

2
HTML 代码
        <input type="text" onkeypress="checkPass();" name="password" class="form-control" id="password" placeholder="Password" required>

        <input type="text" onkeypress="checkPass();" name="rpassword" class="form-control" id="rpassword" placeholder="Retype Password" required>

JS 代码

function checkPass(){
         var pass  = document.getElementById("password").value;
         var rpass  = document.getElementById("rpassword").value;
        if(pass != rpass){
            document.getElementById("submit").disabled = true;
            $('.missmatch').html("Entered Password is not matching!! Try Again");
        }else{
            $('.missmatch').html("");
            document.getElementById("submit").disabled = false;
        }
}

0
$box = $('input[name=showPassword]');

$box.focus(function(){
    if ($(this).is(':checked')) {
        $('input[name=pswd]').attr('type', 'password');    
    } else {
        $('input[name=pswd]').attr('type', 'text');
    }
})

1
你能否详细解释一下你的答案,并为所提供的解决方案添加更多描述? - abarisone

0
你可以通过简单的 JavaScript 来检查确认密码。
HTML。
<input type="password" name="password" required>
<input type="password" name="confirmpassword" onkeypress="register()" required>
<div id="checkconfirm"></div>

并且使用JavaScript

   function register() {

    var password= document.getElementById('password').value ;
    var confirm= document.getElementById('confirmpassword').value;

    if (confirm!=password){
      var field = document.getElementById("checkconfirm")
      field.innerHTML = "not match";
    }
  }

你也可以使用onkeyup而不是onkeypress。


0

尝试像这样使用jQuery

$('input[type=submit]').click(function(e){
if($("#password").val() == "")
{
alert("please enter password");
return false;
}
});

同时在 HTML 的头部添加这行代码

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>

0
$('input[type=submit]').on('click', validate);


function validate() {
  var password1 = $("#password1").val();
  var password2 = $("#password2").val();

    if(password1 == password2) {
       $("#validate-status").text("valid");        
    }
    else {
        $("#validate-status").text("invalid");  
    } 
}

逻辑是在键盘松开时检查两个字段中的值是否匹配。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接