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

时间:2014-02-12 11:57:58

标签: javascript jquery ajax

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

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

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

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

15 个答案:

答案 0 :(得分:48)

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

答案 1 :(得分:9)

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

答案 2 :(得分:3)

使用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相对应。这样当视障人士使用屏幕阅读器调出表单字段时,就会知道文本属于哪个字段。

答案 3 :(得分:2)

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>

答案 4 :(得分:2)

使用本地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>

答案 5 :(得分:1)

  

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

答案 6 :(得分: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>

答案 7 :(得分: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");  
    } 
}

如果两个字段中的值匹配,则逻辑是检查密钥。

答案 8 :(得分:0)

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

希望它可以帮到你

答案 9 :(得分:0)

试试这个;

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

答案 10 :(得分:0)

如果没有点击按钮,您将必须收听输入字段的更改事件

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" />

希望这可以帮助你

答案 11 :(得分: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');
    }
})

答案 12 :(得分: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。

答案 13 :(得分:0)

#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>

#my修改:

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

答案 14 :(得分:0)

我认为此示例适合检查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;