how to check confirm password field in form without reloading page

后端 未结 15 1796
青春惊慌失措
青春惊慌失措 2020-12-12 13:58

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.

相关标签:
15条回答
  • 2020-12-12 14:16
    $('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.

    • Working fiddle: http://jsfiddle.net/dbwMY/
    • More details here: Checking password match while typing
    0 讨论(0)
  • 2020-12-12 14:17

    Solution Using 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. 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. 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.

    0 讨论(0)
  • 2020-12-12 14:17

    The code proposed by #Chandrahasa Rai works almost perfectly good, with one exception!

    When triggering function checkPass(), i changed onkeypress to onkeyup so the last key pressed can be processed too. 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". You have to give it a chance by letting key go up :) Now everything should be working fine!

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

    #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>
    
    0 讨论(0)
  • 2020-12-12 14:19

    try using jquery like this

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

    also add this line in head of html

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
    
    0 讨论(0)
  • 2020-12-12 14:21

    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;
            }
    }
    
    0 讨论(0)
  • 2020-12-12 14:25
       <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

    0 讨论(0)
提交回复
热议问题