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

rav*_*avi 35 javascript ajax jquery

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

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

以下是我的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>
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点?在此先感谢您的帮助.

ael*_*lor 64

我们将研究实现这一目标的两种方法.有和没有使用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');
});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

这里是小提琴: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';
  }
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

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


rjh*_*dby 11

如果你不想使用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;
    }
}
Run Code Online (Sandbox Code Playgroud)
<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/>
Run Code Online (Sandbox Code Playgroud)


lag*_*lex 11

使用原生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');
  }
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

  • 这是最有效、最简单、最棒、最好的方法。 (2认同)

Nat*_*ate 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>
Run Code Online (Sandbox Code Playgroud)

并相应地更新您的表格:

<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>
Run Code Online (Sandbox Code Playgroud)

这将完全满足您的要求

  • 不点击注册按钮的情况下验证密码和确认字段是否相同
  • 如果密码和确认密码字段不匹配,它将确认密码字段旁边放置一条错误消息并禁用注册按钮

建议不要对每个按键都使用 keyup 事件侦听器,因为实际上您只需要在用户完成输入信息时对其进行评估。如果有人在慢速机器上快速打字,他们可能会感觉到滞后,因为每次击键都会启动该功能。

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