【问题标题】:how to check confirm password field in form without reloading page如何在不重新加载页面的情况下检查表单中的确认密码字段
【发布时间】:2014-03-10 17:48:45
【问题描述】:

我有一个项目,我必须在其中添加一个注册表单,并且我想验证密码和确认字段是否相等,而无需单击注册按钮。

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

以下是我的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>

有没有办法做到这一点?提前感谢您的帮助。

【问题讨论】:

标签: javascript jquery ajax


【解决方案1】:

我们将研究两种方法来实现这一目标。使用和不使用 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>

这是小提琴:http://jsfiddle.net/aelor/F6sEv/324/

【讨论】:

  • $('#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'); }); 也是对同一代码的另一种修改,它在修改 2 个密码输入中的每一个时执行检查。如果他们输入两个匹配项,然后不小心修改了密码字段,或者如果他们更改了密码字段,它将更新匹配状态。 jsfiddle.net/C3rMw
  • 对您的脚本稍作改动,让它看起来更好看!不过答案很好。这是其他人未来参考的小提琴:jsfiddle.net/F6sEv/52
  • @AbhishekGhosh 这个小提琴在不使用任何 js 库的情况下工作吗,奇怪?
  • @PhpBeginner: 这是基本的 Javascript.. 它没有使用 JS 库:)
  • @aelor :不确定其他人是否有同样的问题。我输入了密码,然后正在输入“确认密码”数据 - 立即显示“密码匹配”,但当我完成输入“确认密码”详细信息时,显示“密码不匹配”。即使我输入了正确的 ConfrimPassword 或没有始终显示“密码不匹配”消息。这是我第一次进行 UI 开发。如果我在任何地方错了,希望大家纠正我:)
【解决方案2】:

如果你不想使用 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/>

【讨论】:

    【解决方案3】:

    使用原生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】:

    使用 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 吗?
    【解决方案5】:
    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>
    

    【讨论】:

      【解决方案6】:

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

      【讨论】:

        【解决方案7】:

        尝试像这样使用 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>
        

        【讨论】:

          【解决方案8】:
          $('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");  
              } 
          }
          

          逻辑是检查 keyup 是否两个字段中的值匹配。

          【讨论】:

            【解决方案9】:
               <form id="form" name="form" method="post" action="registration.php" onsubmit="return check()"> 
                   ....
               </form>
            
            <script>
              $("#form").submit(function(){
                 if($("#password").val()!=$("#confirm_password").val())
                 {
                     alert("password should be same");
                     return false;
                 }
             })
            </script>
            

            希望对你有帮助

            【讨论】:

              【解决方案10】:

              试试这个;

              CSS

              #indicator{
                  width:20px;
                  height:20px;
                  display:block;
                  border-radius:10px;
              }
              .green{
                  background-color:green; 
                  display:block;
              }
              .red{
                  background-color:red;   
                  display:block;
              }
              

              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" id="password" /></label>      <br>
                  <label>confirm password:
                  <input type="password" name="confirm_password" id="confirm_password" /><span id="indicator"></span> <br>
                  </label>
                  <label>
                  <input type="submit" name="submit" id="regbtn"  value="registration"  />
                  </label>
              </form>
              

              JQuery

              $('#confirm_password').keyup(function(){
                  var pass    =   $('#password').val();
                  var cpass   =   $('#confirm_password').val();
                  if(pass!=cpass){
                      $('#indicator').attr({class:'red'});
                      $('#regbtn').attr({disabled:true});
                  }
                  else{
                      $('#indicator').attr({class:'green'});
                      $('#regbtn').attr({disabled:false});
                  }
              });
              

              【讨论】:

                【解决方案11】:

                不点击按钮,您将不得不监听输入字段的更改事件

                var confirmField = document.getElementById("confirm_password");
                var passwordField = document.getElementById("password");
                
                function checkPasswordMatch(){
                    var status = document.getElementById("password_status");
                    var submit = document.getElementById("submit");
                
                    status.innerHTML = "";
                    submit.removeAttribute("disabled");
                
                    if(confirmField.value === "")
                        return;
                
                    if(passwordField.value === confirmField.value)
                        return;
                
                    status.innerHTML = "Passwords don't match";
                    submit.setAttribute("disabled", "disabled");
                }
                
                passWordField.addEventListener("change", function(event){
                    checkPasswordMatch();
                });
                confirmField.addEventListener("change", function(event){
                    checkPasswordMatch();
                });
                

                然后将状态元素添加到您的 html:

                <p id="password_status"></p>
                

                并将提交按钮 id 设置为submit

                ... id="submit" />
                

                希望对你有帮助

                【讨论】:

                  【解决方案12】:
                  $box = $('input[name=showPassword]');
                  
                  $box.focus(function(){
                      if ($(this).is(':checked')) {
                          $('input[name=pswd]').attr('type', 'password');    
                      } else {
                          $('input[name=pswd]').attr('type', 'text');
                      }
                  })
                  

                  【讨论】:

                  • 能否请您详细说明您的答案,添加更多关于您提供的解决方案的描述?
                  【解决方案13】:

                  您可以通过简单的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。

                  【讨论】:

                    【解决方案14】:

                    #Chandrahasa Rai 提出的代码 效果几乎完美无缺,只有一个例外!

                    在触发checkPass()函数时,我将onkeypress更改为onkeyup,所以最后按下的键也可以处理。否则当您输入密码时,例如:“1234”,当您输入最后一个键“4”时,脚本会在处理“4”之前触发checkPass(),因此它实际上会检查“123”而不是“1234”。您必须通过让键上升来给它一个机会:) 现在一切都应该正常了!

                    #Chandrahasa Rai, 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>
                    

                    #我的修改:

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

                    【讨论】:

                      【解决方案15】:

                      我觉得这个例子很好看https://codepen.io/diegoleme/pen/surIK

                      我可以在这里引用代码

                      <form class="pure-form">
                          <fieldset>
                              <legend>Confirm password with HTML5</legend>
                      
                              <input type="password" placeholder="Password" id="password" required>
                              <input type="password" placeholder="Confirm Password" id="confirm_password" required>
                      
                              <button type="submit" class="pure-button pure-button-primary">Confirm</button>
                          </fieldset>
                      </form>
                      

                      var password = document.getElementById("password")
                        , confirm_password = document.getElementById("confirm_password");
                      
                      function validatePassword(){
                        if(password.value != confirm_password.value) {
                          confirm_password.setCustomValidity("Passwords Don't Match");
                        } else {
                          confirm_password.setCustomValidity('');
                        }
                      }
                      
                      password.onchange = validatePassword;
                      confirm_password.onkeyup = validatePassword;
                      

                      【讨论】:

                        猜你喜欢
                        • 1970-01-01
                        • 1970-01-01
                        • 2021-01-09
                        • 2019-11-18
                        • 2015-07-31
                        • 1970-01-01
                        • 2016-12-05
                        • 1970-01-01
                        相关资源
                        最近更新 更多