简体   繁体   English

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

[英]how to check confirm password field in form without reloading page

I have a project in which I have to add a registration form and I want to to validate that the password and confirm fields are equal without clicking the register button.我有一个项目,我必须在其中添加一个注册表单,我想验证密码和确认字段是否相同,而无需单击注册按钮。

If password and confirm password field will not match, then I also want to put an error message at side of confirm password field and disable registration button.如果密码和确认密码字段不匹配,那么我还想在确认密码字段旁边放置一条错误消息并禁用注册按钮。

following is my html code..以下是我的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>

Is there any way to do this?有没有办法做到这一点? Thanks in advance for any help.在此先感谢您的帮助。

We will be looking at two approaches to achieve this.我们将研究两种方法来实现这一目标。 With and without using jQuery.使用和不使用 jQuery。

1. Using jQuery 1. 使用 jQuery

You need to add a keyup function to both of your password and confirm password fields.您需要在密码和确认密码字段中添加keyup功能。 The reason being that the text equality should be checked even if the password field changes.原因是即使password字段更改,也应检查文本是否相等。 Thanks @kdjernigan for pointing that out感谢@kdjernigan 指出这一点

In this way, when you type in the field you will know if the password is same or not:这样,当您在字段中键入时,您将知道密码是否相同:

 $('#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>

and here is the fiddle: http://jsfiddle.net/aelor/F6sEv/325/这是小提琴: http : //jsfiddle.net/aelor/F6sEv/325/

2. Without using jQuery 2.不使用jQuery

We will use the onkeyup event of javascript on both the fields to achieve the same effect.我们将在两个字段上使用 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>

and here is the fiddle: http://jsfiddle.net/aelor/F6sEv/324/这是小提琴: http : //jsfiddle.net/aelor/F6sEv/324/

If you don't want use jQuery:如果您不想使用 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/>

Using Native setCustomValidity使用原生setCustomValidity

Compare the password/confirm-password input values on their change event and setCustomValidity accordingly:比较其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>

Solution Using jQuery使用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>

And update your form accordingly:并相应地更新您的表格:

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

This will do precisely what you asked for :这将完全满足您的要求

  • validate that the password and confirm fields are equal without clicking the register button无需单击注册按钮即可验证密码和确认字段是否相同
  • If password and confirm password field will not match it will place an error message at the side of confirm password field and disable registration button如果密码和确认密码字段不匹配,它将确认密码字段旁边放置一条错误消息并禁用注册按钮

It is advisable not to use a keyup event listener for every keypress because really you only need to evaluate it when the user is done entering information.建议不要对每个按键都使用 keyup 事件侦听器,因为实际上您只需要在用户完成输入信息时对其进行评估。 If someone types quickly on a slow machine, they may perceive lag as each keystroke will kick off the function.如果有人在慢速机器上快速打字,他们可能会感觉到滞后,因为每次击键都会启动该功能。

Also, in your form you are using labels wrong.此外,在您的表单中,您使用的标签是错误的。 The label element has a "for" attribute which should correspond with the id of the form element. label 元素有一个“for”属性,它应该与表单元素的 id 相对应。 This is so that when visually impaired people use a screen reader to call out the form field, it will know text belongs to which field.这样,当视障人士使用屏幕阅读器调出表单字段时,它就会知道文本属于哪个字段。

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>

HTML CODE代码

        <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 CODE代码

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

try using jquery like this尝试像这样使用 jquery

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

also add this line in head of html还要在 html 的头部添加这一行

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
$('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");  
    } 
}

Logic is to check on keyup if the value in both fields match or not.逻辑是检查 keyup 是否两个字段中的值匹配。

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

hope it may help you希望它可以帮助你

Try this one ;试试这个;

CSS CSS

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

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

WITHOUT clicking the button you will have to listen to the change event of the input fields无需单击按钮,您将不得不收听输入字段的更改事件

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

then add the status element to your html:然后将状态元素添加到您的 html:

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

and set the submit button id to submit并设置提交按钮 id 以submit

... id="submit" />

hope this helps you希望这对你有帮助

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

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

You can check confirm password by only simple javascript您可以仅通过简单的 javascript 来检查确认密码

html html

<input type="password" name="password" required>
<input type="password" name="confirmpassword" onkeypress="register()" required>
<div id="checkconfirm"></div>

and in javascript在 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";
    }
  }

Also you can use onkeyup instead of onkeypress.您也可以使用 onkeyup 而不是 onkeypress。

The code proposed by #Chandrahasa Rai works almost perfectly good, with one exception! #Chandrahasa Rai 提出的代码几乎完美运行,只有一个例外!

When triggering function checkPass() , i changed onkeypress to onkeyup so the last key pressed can be processed too.触发函数checkPass() ,我将onkeypress更改为onkeyup以便也可以处理最后按下的键。 Otherwise when You type a password, for example: "1234", when You type the last key "4", the script triggers checkPass() before processing "4", so it actually checks "123" instead of "1234".否则,当您输入密码时,例如:“1234”,当您输入最后一个键“4”时,脚本会在处理“4”之前触发checkPass() ,因此它实际上会检查“123”而不是“1234”。 You have to give it a chance by letting key go up :) Now everything should be working fine!你必须通过让键上升来给它一个机会:) 现在一切都应该正常工作了!

#Chandrahasa Rai, HTML code: #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 modification: #我的修改:

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

I think this example is good to check https://codepen.io/diegoleme/pen/surIK我认为这个例子很好检查https://codepen.io/diegoleme/pen/surIK

I can quote code here我可以在这里引用代码

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

and

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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在不重新加载页面或单击按钮的情况下检查表单中的确认密码字段? - how to check confirm password field in form without reloading page or clicking on button? 如何使用确认密码字段检查密码字段 - how to check password field with confirm password field 如何在不重新加载页面的情况下提交表单数据 - How to submit a form data without reloading the page 如何在不重新加载页面的情况下提交表单 - How to submit form without the page reloading 如何在不重定向或重新加载页面的情况下更新字段/发布表单? - How can i update a field / post a form without redirecting or reloading a page? 如何在不重新加载页面的情况下触发“保存密码” Web浏览器对话框? - How to trigger the “Save password” web browser dialog without reloading the page? 无需重新加载页面即可提交表单 - Submit form without page reloading 在没有jQuery的情况下如何提交表单而不重新加载页面? - How to submit form without reloading page, without jQuery? 我可以知道一种方法来提交数据到 Firebase 而不提交 Angular 8 表格中的“确认密码”字段吗? - Can I know a way to submit data to Firebase without submitting the “Confirm-Password” field in Angular 8 Form? 在允许用户提交表单 JS 之前,我如何检查密码是否与确认密码匹配 - How do I check to see is password matches confirm password before user is allowed to submit the form JS
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM