TIL 01.27

새양말·2023년 1월 30일
0

내일배움캠프TIL

목록 보기
57/74
post-thumbnail

로그인의 유효성 검사 만들기

시도) 버튼을 눌렀을 때 결과가 나오도록 했음.

유효성 검사 함수를 따로 만들고 리턴문에 연결.

const validateInputs = () => {
    if (!email) {
      alert("email을 입력해주세요.");
      emailRef.current.focus();
      return true;
    }
    if (!pw) {
      alert("password를 입력해주세요.");
      pwRef.current.focus();
      return true;
    }
    const matchedEmail = email.match(emailRegex);
    const matchedPw = pw.match(pwRegex);

    if (matchedEmail === null) {
      alert("이메일 형식에 맞게 입력해 주세요.");
      emailRef.current.focus();
      return true;
    }
    if (matchedPw === null) {
      alert("비밀번호는 8자리 이상 영문자, 숫자, 특수문자 조합이어야 합니다.");
      pwRef.current.focus();
      return true;
    }
  };

더 나은 방법) 입력을 할 때마다 바로 검사 결과 띄움.
함수를 아이디, 닉네임, 비밀번호, 비밀번호 확인까지 각각 다 만들어주기.

각각의 함수들 예시

//* id (이메일)
  const onChangeId = (e: ChangeEvent<HTMLInputElement>) => {
    const currentId = e.target.value;
    setId(currentId);
    const idRegex =
      /([\w-.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
    if (!idRegex.test(currentId)) {
      setIdErrMsg('! 잘못된 이메일 주소입니다.');
      setIsId(false);
    } else {
      setIdErrMsg('사용 가능합니다.');
      setIsId(true);
    }
  };

리턴문

<Error>
          {id.length > 0 && (
            <span className={`message ${isId ? 'success' : 'error'}`}>
              {idErrMsg}
            </span>
          )}
        </Error>

사실 {idErrMsg} 이렇게만 쓰고 글씨색 변환은 따로 함수를 만들어서 적용하고싶었는데 잘 안됐다.

profile
매번 기합넣는 양말

0개의 댓글