Подтвердить что ты не робот

Как проверить поле подтверждения пароля в форме без перезагрузки страницы

У меня есть проект, в котором я должен добавить регистрационную форму, и я хочу проверить, что поля пароля и подтверждения равны без нажатия кнопки регистрации.

Если пароль и подтверждение пароля не совпадают, тогда я также хочу поставить сообщение об ошибке на стороне поля подтверждения пароля и отключить кнопку регистрации.

следующий мой 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>

Есть ли способ сделать это? Заранее благодарим за любую помощь.

4b9b3361

Ответ 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>

Ответ 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

Решение Использование 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 имеет атрибут "для", который должен соответствовать идентификатору элемента формы. Это значит, что, когда люди с ослабленным зрением используют экранный ридер для вызова поля формы, он будет знать, что текст принадлежит тому полю.

Ответ 4

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>

Ответ 5

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

Ответ 6

попробуйте использовать jquery, подобный этому

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

также добавить эту строку в head html

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>

Ответ 7

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

   <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

Попробуйте это:

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

Без нажатия кнопки вам нужно будет прослушать событие изменения полей ввода

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>

и установите идентификатор кнопки отправки submit

... id="submit" />

надеюсь, что это поможет вам

Ответ 11

$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

Вы можете проверить подтверждение пароля только с помощью простого 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.