Language/JavaScript (WEB)

🌐 Confirm password 폼 μ‰½κ²Œ κ΅¬ν˜„ν•˜κΈ°

인파_ 2022. 5. 29. 11:44

Confirm password

λΉ„λ°€λ²ˆν˜Έ μž¬ν™•μΈ κΈ°λŠ₯ κ΅¬ν˜„

두 input μž…λ ₯ νƒœκ·Έμ°½μ΄ 있고, 이 두 input창의 κ°’(λΉ„λ°€λ²ˆν˜Έ)κ°€ κ°™μ•„μ•Ό submit이 되게 μ²˜λ¦¬ν•  경우, κ΅¬ν˜„ν•˜λŠ” 방법은 μžλ°”μŠ€ν¬λ¦½νŠΈμ™€ css둜 ν•˜λ“œμ½”λ”©ν•˜κ±°λ‚˜ λ“± μ—¬λŸ¬κ°€μ§€κ°€ μ‘΄μž¬ν•œλ‹€.

그쀑, μ΄λ²ˆμ‹œκ°„μ—λŠ” setCustomValidity() λ₯Ό 톡해 κ°„λ‹¨ν•˜κ²Œ Confirm passwordλ₯Ό κ΅¬ν˜„ν•΄λ³΄λŠ” μ‹œκ°„μ„ 가져보겠닀.

 

setCustomValidity

HTMLObjectElement μΈν„°νŽ˜μ΄μŠ€ 의 setCustomValidity() λ©”μ„œλ“œ λŠ” μš”μ†Œμ— λŒ€ν•œ μ‚¬μš©μž μ •μ˜ μœ νš¨μ„± λ©”μ‹œμ§€λ₯Ό μ„€μ •ν•œλ‹€.

μ•„λž˜μ‚¬μ§„μ—μ„œ 볼수 μžˆλ“―μ΄ input νƒ€μž…μ— μ μ ˆν•˜μ§€ μ•ŠλŠ” 값을 λ„£μ—ˆμ„λ•Œ λΈŒλΌμš°μ €μ—μ„œ λ„μš°λŠ” λŠλ‚Œν‘œ λ§ν’μ„ μ˜ λ‚΄μš©μ„ μ„€μ • ν•΄ μ€„μˆ˜ μžˆλ‹€.

Confirm password

 

단, 였λ₯˜λ©”μ„Έμ§€ λ§ν’μ„ μ˜ λ‚΄μš©μ„ apiλ₯Ό 톡해 μ„€μ •ν•΄μ£Όκ²Œ 되면, 였λ₯˜ λ©”μ‹œμ§€κ°€ λΉ„μ–΄ μžˆμ§€ μ•Šμ€ ν•œ 양식은 μœ νš¨μ„± 검사λ₯Ό ν†΅κ³Όν•˜μ§€ μ•Šκ³  μ œμΆœλ˜μ§€ μ•ŠλŠ” λ‹€λŠ” νŠΉμ§•μ΄ μžˆλŠ”λ°, 이λ₯Ό μ΄μš©ν•΄ λΉ„λ°€λ²ˆν˜Έ μž¬ν™•μΈ λ‘œμ§μ„ κ°„λ‹¨ν•˜κ²Œ κ΅¬ν˜„ν•  수 μžˆλ‹€.

<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) { // 만일 두 인풋 ν•„λ“œκ°’μ΄ κ°™μ§€ μ•Šμ„ 경우
    // setCustomValidity의 값을 μ§€μ •ν•΄ 무쑰건 κ²½κ³  ν‘œμ‹œκ°€ λ‚˜κ²Œ ν•˜κ³ 
    confirm_password.setCustomValidity("Passwords Don't Match"); 
  } 
  else { // 만일 두 인풋 ν•„λ“œκ°’μ΄ 같을 경우
    // 였λ₯˜κ°€ μ—†μœΌλ©΄ λ©”μ‹œμ§€λ₯Ό 빈 λ¬Έμžμ—΄λ‘œ μ„€μ •ν•΄μ•Όν•œλ‹€. 였λ₯˜ λ©”μ‹œμ§€κ°€ λΉ„μ–΄ μžˆμ§€ μ•Šμ€ ν•œ 양식은 μœ νš¨μ„± 검사λ₯Ό ν†΅κ³Όν•˜μ§€ μ•Šκ³  μ œμΆœλ˜μ§€ μ•ŠλŠ”λ‹€.
    // λ”°λΌμ„œ λΉˆκ°’μ„ μ£Όμ–΄ submit 처리되게 ν•œλ‹€
    confirm_password.setCustomValidity(''); 
  }
}

password.onchange = validatePassword;
confirm_password.onkeyup = validatePassword;

See the Pen Confirm PWD by barzz12 (@inpaSkyrim) on CodePen.