로그인창 아이디나 비밀번호 미입력시 하단에 경고문구 뜨게하기

<form action="#" method="post" name="login">
 <fieldset>
  <legend>Log In</legend>
  <input type="text" placeholder="ID 아이디" maxlength="20" name="id" id="
  <br>
  <input type="password" placeholder="PW 비밀번호" maxlength="20" name="pw" id="
  <br>
  <input type="submit" value="확인">
  <br>
  <span class="message" id="message"></span>
  </fieldset>
</form>


✅html
1) form 태그를 작성
2) 아이디, 패스워드, 확인 버튼 생성
3) 하단에 빈 span태그를 작성해준다
4) span태그에 class와 id명을 설정하여 css에서 속성과 javascript에서 속성을 설정 할 수 있게한다


window.onload = function() {
    var login = document.login;
    login.onsubmit = function() {
        if(!login.id.value){
            span = document.getElementById("message");
            txt = document.createTextNode("아이디를 입력해주세요");
            span.appendChild(txt);
            login.id.focus();
            return false;
        }
        if(!login.pw.value){
            span = document.getElementById("message");
            txt = document.createTextNode("비밀번호를 입력해주세요");
            span.appendChild(txt);
            login.pw.focus();
            return false;
        }
        else{
            span = document.getElementById("message");
            txt = document.createTextNode("잘못입력하였습니다. 아이디와 비밀번호를 확인해주세요");
            span.appendChild(txt);
            login.id.focus();
            return false;
        }
    }
}

✅Java script 방법1 ->실패
1) window.onload 함수를 선언
2) login객체를 선언
3) login 함수를 작성 if문을 활용
4) 부정문(!)을 활용하여 로그인 작성안할경우 결과값을 입력
5) if문을 만족할 경우 span에 텍스트 생성과 아이디칸에 포커스가 잡힐 수 있게 객체 생성
6) true 페이지로 넘어가지 않게 false를 반환
*pw 부분도 동일

7) else는 if문 의외의 상황시 발생
8) 성공시 페이지가 넘어가지 않도록 잘못입력하였다는 메시지와 false반환
-> 무한 flase로 계속 해서 span이 반복됨

✔️span이 확인을 누르면 무한 반복
✔️결과 값을 경고창 형식으로 바꾸고 함수를 빠져나갈 수 있게 성공 경로를 작성할 예정

 

function validate() {
    const regId = /^[a-zA-Z0-9]{4,12}$/;
    // 아이디 정규식
    const regPw = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@$!%*#?&])[A-Za-z\d$@$!%*#?&]{8,}$/;
    // 패스워드 정규식, 최소 8 자, 최소 하나의 문자, 하나의 숫자 및 하나의 특수 문자
    const regNull  = /\s/g;
    // 빈값
    
    let id = document.getElementById("id");
    let pw = document.getElementById("pw");
    // 정규식 조건에 위배되었을 때, alert이 출력되는 함수였다.
    // 요 값이 true이고 이걸 부정한 조건(false)일 때 넘어간다.

    // 아이디 정규식 확인
    if (!checkReg(regId, id, "아이디는 4~12자의 영문 대소문자와 숫자로만 입력")) {
        return false;
    }

    // 비밀번호 정규식 확인
    if (!checkReg(regPw, pw, "최소 8자, 최소 하나의 문자, 숫자, 특수 문자를 포함하여 입력")) {
        return false;
    }
    // 비밀번호 빈값확인
    if (!checkNull(pw, "비밀번호를 입력해 주세요")) {
        return false;
    }
}
// 정규식 확인
function checkReg(reg, what, message) {
    // 정규식에 위배되지 않았을때
    let alertMSG = what.parentNode.lastElementChild;
    if (reg.test(what.value)) {
        alertMSG.textContent = ""; // 메시지 공백화
        return true;
    }
    // 정규식에 위배되었을때
    alertMSG.textContent = message; // 메시지 출력
    what.value = ""; // 해당 위치 공백화
    what.focus(); // 해당위치로 포커싱
}
// 빈값 확인
function checkNull(what, message) {
    // 빈값없음
    let alertMSG = what.parentNode.lastElementChild;
    if (what.value !== "") {
        alertMSG.textContent = "해당페이지는 포트폴리오 사이트로 로그인 할 수 없습니다";
        return true;
    }
    // 빈값확인
    alertMSG.textContent = message; // 메시지 출력
    what.focus(); // 해당위치로 포커싱
}


let inputs = document.querySelectorAll('input');
Array.from(inputs).forEach((eachInput) => {
    eachInput.addEventListener('blur', (e) => validate(e));
});
const validation = document.querySelector('#validation');
validation.addEventListener('click', (e) => validate(e));

✅Java script 방법2 ->성공
1)아이디, 패스워드, 빈값에 대한 정규식 작성
2) 아이디 패스워드 선언
3) id 정규식확인 if문 작성 
4) pw 정규식확인 if문 작성 
5) if문을 만족할 경우 공백화, 포커싱을 작성(무한 span방지를 위해 공백화작성)

✔️span이 확인을 누르면 무한 반복해결
✔️빈칸 뿐 아니라 정규식에 대한 부분 오류 메시지 작성

✔️ 하단 let const부분 한번 더 보기

+ Recent posts