[JS] 로그인폼 Vaildation Check(유효성 검사)

또띠·2022년 10월 17일
1

로그인폼으로 Javascript 연습을 하다 더 나은 스크립트를 짤 수 없을까 라는 고민을 시작으로 'vaildation check(유효성 검사)' 라는 것을 알게 되었다.

❓ vaildation check(유효성 검사) 란?
사용자가 입력한 값이 서버로 넘어가기전에 올바른지 체크를 하는 것

참고로 유효성 검사는 클라이언트에서 먼저 하고 서버쪽에서도 또 한다고 한다.
왜냐하면 서버 입장에서 클라이언트에서 온 데이터를 무조건 믿을 수 없기 때문...!

⭐알려주신 Liz님 감사합니다 :)


우선 html로 간단하게 로그인 폼을 아래와 같이 짜 보았다.

 	<main>
        <form name="welcome" method="post" class="login">
            <div>
                <label for="userID">ID</label>
                <input type="text" id="userID" onkeydown="if(event.keyCode == 13) loginChk()">
            </div>
            <div>
                <label for="userPW">PW</label>
                <input type="password" id="userPW" onkeydown="if(event.keyCode == 13) loginChk()">
            </div>
            <div class="btns">
                <button type="button" class="btn" id="loginBtn" onclick="loginChk()">Login</button>
                <button type="button" class="btn" id="joinBtn"><a href="join.html">Join</a></button>
            </div>
        </form>
    </main>

그리고 ID와 PW에 유효성 검사를 위한 스크립트를 아래와 같이 작성해 보았다.

<script>
  var id = document.getElementById('userID');
  var pw = document.getElementById('userPW');
  var loginBtn = document.getElementById('loginBtn');
  var joinBtn = document.getElementById('joinBtn');

  // 로그인 유효성 체크 바리데이션
  	function loginChk() {
     	if(!id.value){
         	alert('아이디를 입력해주세요.');
            id.focus();
            return;
           }

        if(!pw.value){
           alert('비밀번호를 입력해주세요.');
           pw.focus();
           return;
          }
        }
 </script>

여기서 포인트는 각각의 id와 pw 값을 확인 후 같지 않으면 어디 부분이 잘못되었는지를 alert을 통해 사용자에게 알리게 된다.

또한 값이 틀리면 친절하게 해당 input으로 focus를 주어 사용자의 편리성을 더해준다.

정리하며...

유효성 검사를 알게 된 후 로그인 값 확인을 보다 간편하지만 정밀하게 할 수 있게 되었고 굉장히 자주 쓰이는 소스라는걸 알게 되었다!

스크립트를 작성하기전 어떻게 짤것인지 설계를 먼저 생각해보고 작성하는 습관을 길러두어야겠다.

profile
✨ 𝑬𝒗𝒆𝒓𝒚𝒕𝒉𝒊𝒏𝒈 𝒄𝒐𝒎𝒆𝒔 𝒕𝒐 𝒉𝒊𝒎 𝒘𝒉𝒐 𝒉𝒖𝒔𝒕𝒍𝒆𝒔 𝒘𝒉𝒊𝒍𝒆 𝒉𝒆 𝒘𝒂𝒊𝒕𝒔. ✨

0개의 댓글