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.