programing

페이지를 새로고침하지 않고 형식의 비밀번호 확인 필드를 확인하는 방법

i4 2023. 4. 6. 20:47
반응형

페이지를 새로고침하지 않고 형식의 비밀번호 확인 필드를 확인하는 방법

등록 양식을 추가해야 하는 프로젝트가 있는데 등록 버튼을 클릭하지 않고 비밀번호와 확인 필드가 동일한지 확인하고 싶습니다.

비밀번호와 비밀번호 확인 필드가 일치하지 않으면 비밀번호 확인 필드 옆에 오류 메시지를 표시하고 등록 버튼을 비활성화합니다.

다음은 나의 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>

어떻게 할 수 있을까요?

이를 실현하기 위해 두 가지 접근방식을 검토하겠습니다.jQuery 사용 여부

1. jQuery 사용

비밀번호와 비밀번호 확인 필드에 모두 키업 기능을 추가해야 합니다.그 이유는 텍스트의 동일성을 체크해야 하기 때문입니다.password필드를 변경합니다.@ @kdjernigan @kdjernigan @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/

네이티브 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>

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

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>

이렇게 하면 요청하신 대로 정확하게 수행할 수 있습니다.

  • 등록 버튼을 클릭하지 않고 비밀번호와 확인 필드가 동일한지 확인합니다.
  • 비밀번호와 비밀번호 확인 필드가 일치하지 않으면 비밀번호 확인 필드 옆에 오류 메시지가 표시되고 등록 버튼을 비활성화합니다.

모든 키 누르기에 대해 키 업 이벤트청취기를 사용하지 않는 것이 좋습니다.사용자가 정보를 입력했을 때만 키 업 이벤트청취기를 평가할 필요가 있기 때문입니다.느린 기계에서 빠르게 타이핑을 하면 각 키 입력이 기능을 시작하기 때문에 지연이 발생할 수 있습니다.

또, 당신의 폼에서는 라벨을 잘못 사용하고 있습니다.라벨 요소에는 폼 요소의 ID에 대응하는 "for" 속성이 있습니다.시각장애인이 화면 리더를 사용하여 폼 필드를 호출하면 텍스트가 어느 필드에 속하는지 알 수 있습니다.

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

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

이렇게 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>
$('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");  
    } 
}

로직은 키업 시 양쪽 필드의 값이 일치하는지 여부를 확인하는 것입니다.

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

도움이 되길 바란다

이거 먹어봐;

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

버튼을 클릭하지 않고 입력 필드의 변경 이벤트를 들어야 합니다.

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

... id="submit" />

이것이 너에게 도움이 되길 바란다.

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

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

간단한 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";
    }
  }

또한 키 누르기 대신 키 누르기를 사용할 수도 있습니다.

#Chandrahasa Rai가 제안한 코드는 한 가지 예외를 제외하고는 거의 완벽하게 작동합니다!

기능을 트리거할 때checkPass(), 나는 변했다.onkeypress로.onkeyup마지막으로 누른 키도 처리할 수 있습니다.그렇지 않으면 암호를 입력할 때(예: "1234"), 마지막 키 "4"를 입력하면 스크립트가 트리거됩니다.checkPass()"4"를 처리하기 전에 "1234"가 아닌 "123"을 체크합니다.키를 올려서 기회를 줘야 합니다:) 이제 모든 것이 정상적으로 작동해야 합니다.

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

#수정:

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

이 예는 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;

언급URL : https://stackoverflow.com/questions/21727317/how-to-check-confirm-password-field-in-form-without-reloading-page

반응형