회원가입 기능

가연·2023년 2월 22일
0

date.now 리팩토링

목록 보기
4/7

바닐라js 로 회원가입 기능을 만든것을 리팩토링하자.
모듈을 만들고, 정규표현식을 추가했으며, 하나의 함수에 하나의 기능만 수행하도록 나누었다.

깃허브 Date.now 리팩토링


모듈 안에 에러메세지 함수를 넣어 export 했다. (es6방식으로 함)

// 모듈
export const caution = {
  essentialInfo(box) {
    box.innerText = "필수 정보입니다.";
  },

  cautionMessage(box, text) {
    box.innerText = text;
  },
};

이 함수를 사용하기 위해 signup.js파일에 모듈을 import 하고
html 파일의 script에 type="module" 를 추가해주어야 한다.

import { caution } from "../module/func.mjs"; 

const passwordRegex =
  /^(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]).{8,20}$/;

function passwordCorrect() {
  if (psword.value != rePsword.value) {
    caution.cautionMessage(repswordWarn, "비밀번호가 일치하지 않습니다.");
  } else {
    caution.cautionMessage(repswordWarn, "");
    pswordTrue = true;
  }
}

function isValidPassword() {
  if (psword.value == "") {
    caution.essentialInfo(pswordWarn);
  } else {
    if (!passwordRegex.test(psword.value)) {
      caution.cautionMessage(pswordWarn, "");
      caution.cautionMessage(
        pswordWarn2,
        "비밀번호는 영문자+숫자+특수문자 조합으로 8~20자리 사용해야 합니다."
      );
    } else {
      caution.cautionMessage(pswordWarn2, "");
      passwordCorrect();
    }
  }
}

해당 코드는 비밀번호 유효성검사를 하는 함수이다.

모듈은 상위의 폴더에 있으므로 ../ 으로 경로를 설정해준다.

passwordRegex 는 정규표현식으로 passwordRegex.test(psword.value)는 입력된 비밀번호 값이 정규표현식을 만족하지 못할 경우 false 값이 나온다.
(-> 추가 내용은 추후 '자바스크립트' 에 정리)

isValidPassword 함수는 비밀번호가 입력된다면 정규식으로 검사 후 해당 조건을 만족한 값이라면 passwordCorrect 함수를 호출하게 된다. 이 함수는 비밀번호 재입력시 똑같이 비밀번호를 작성한다면 pswordTrue 라는 불리언값을 true로 바꿔준다.

function signIn(event) {
  event.preventDefault();
  if (!(nameTrue && pswordTrue && emailTrue && birthTrue)) {
    event.preventDefault();
    isValidEmail();
    isValidPassword();
    requiredName();
    requiredBirth();
  } else {
    const UserInfo = collectInformation();
    axios
      .post("http://localhost:8080/api/v1/user/signup", UserInfo, {
        headers: {
          "Content-Type": "application/json",
        },
      })
      .then((res) => {
        console.log(res);
        location.href = "http://localhost:3000/login/";
      })
      .catch((err) => {
        alert(err);
      });
  }
}function signIn(event) {
  event.preventDefault();
  if (!(nameTrue && pswordTrue && emailTrue && birthTrue)) {
    event.preventDefault();
    isValidEmail();
    isValidPassword();
    requiredName();
    requiredBirth();
  } else {
    const UserInfo = collectInformation();
    axios
      .post("http://localhost:8080/api/v1/user/signup", UserInfo, {
        headers: {
          "Content-Type": "application/json",
        },
      })
      .then((res) => {
        console.log(res);
        location.href = "http://localhost:3000/login/";
      })
      .catch((err) => {
        alert(err);
      });
  }
}

signIn 함수는 input값들의 유효성을 검사해서 나온 변수들이 전부 true 값이면 axios를 이용해 입력데이터 객체를 보내준 후, 전달에 성공하면 로그인 창으로 이동해준다.(&&는 모두 참일 때만 전체 식이 참)


결과

0개의 댓글