[React] 회원가입 페이지 유효성 검사하기

Cottonmycotton·2021년 12월 4일
10

React

목록 보기
7/14

리액트를 사용해 회원가입 페이지 레이아웃 및 유효성 검사 기능을 구현하였다. 버튼이 활성화 되기 위한 조건은 아래와 같다.
1) 모든 input창의 입력값이 1자 이상이 될 것.
2) 이메일(ID)은 '@' 와 '.' 두개를 모두 포함할 것.
3) 비밀번호는 특수문자 1자이상 포함 8자 일 것.
4) 체크박스 중 필수항목인 첫번째 칸은 체크가 되어야 할 것.
5) 위 네개의 항목 중 한가지 조건이라도 만족하지 않을 때 버튼을 클릭하면 경고창이 뜬다.

1. useState와 함수를 이용하여 input의 value값 받아오기

const [inputValue, setInputValue] = useState({
  userName: '',
  email: '',
  password: '',
  phoneNumber: '',
  address: '',
});

const { username, email, password, phoneNumber, address } = inputValue;

const handleInput = event => {
  const { name, value } = event.target;
  setInputValue({
    ...inputValue, 
    [name]: value,
  });
};

// jsx코드

return (
  <main className='signUp>
  <form className="signUpInput">
          <div className="nameInput">
            <div className="inputMessage">Name *</div>
            <input
              name="userName"
              onChange={handleInput}
            />
          </div>
          <div className="emailInput">
            <div className="inputMessage">Email(ID) *</div>
            <input
              name="email"
              onChange={handleInput}
            />
          </div>
          <div className="passwordInput">
            <div className="inputMessage">Password *</div>
            <input
              type="password"
              name="password"
              onChange={handleInput}
            />
          </div>
          <div className="phoneNumberInput">
            <div className="inputMessage">Phone Number *</div>
            <input
              name="phoneNumber"
              onChange={handleInput}
            />
          </div>
          <div className="addressInput">
            <div className="inputMessage">Address *</div>
            <input
              name="address"
              onChange={handleInput}
            />
          </div>
        </form>
        <div className="agreeCheckbox">
          <div className="accountCheckboxAgree">
            <input
              type="checkbox"
              className="checkbox"
              onClick={isCheckBoxClicked}
            />
            <span className="checkboxContent">
              I agree to the
              <span className="line">terms&conditions and privacy policy</span>*
            </span>
          </div>
          <div className="accountCheckboxAgree">
            <input type="checkbox" className="checkbox" />
            <span className="checkboxContent">
              I would like to receive you newsletter
            </span>
          </div>
          <span className="checkboxExplain">
            You will be able to set your password after you've confirmed your
            email address
          </span>
        </div>
      </div>
      <div className="signUpBottom">
        <button
          className={
            getIsActive ? 'signUpButtonAction' : 'signUpButtonInaction'
          }
          type="button"
          onClick={handleButtonValid}
        >
          CREATE USER ACCOUNT
        </button>
      </div>
  </main>

2. 이메일 & 비밀번호 유효성 검사

처음엔 변수가 아닌 함수를 만들어 함수안에 로직을 작성했었다. 리팩토링을 한번 거치게 되면서 함수가 아닌 변수를 선언해 값을 넣어주었는데 이유는 아래 로직은 상태가 아닌 값 자체를 나타내는 로직이기 때문에 변수로 나타내주었다.

// 이메일 검사: '@', '.' 이 둘다 포함될것.
const isValidEmail = email.includes('@') && email.includes('.');
// 비밀번호 특수문자 검사를 위한 정규식표현.
const specialLetter = password.search(/[`~!@@#$%^&*|₩₩₩'₩";:₩/?]/gi);
// 특수문자 1자 이상, 전체 8자 이상일것.
const isValidPassword = password.length >= 8 && specialLetter >= 1;

3. 체크박스 검사

초기상태는 체크가 되어있지 않은 상태이니 false로 설정해준다. input에 onClick이벤트를 달아준뒤 작성한 함수를 넣어준다. 클릭이 될 때 마다 상태가 false -> true 다시 false -> true 이런식으로 바뀜. 유효성 검사를 할땐 isCheckBoxClicked값이 true일 때를 조건으로 넣어준다.

const [checkBoxActive, setCheckboxActive] = useState(false);
const isCheckBoxClicked = () => {
  setCheckBoxActive(!checkBoxActive);
};

// jsx
 <input
  type="checkbox"
  className="checkbox"
  onClick={isCheckBoxClicked} />

4. 버튼 활성화 하기

// 모든 input의 value가 1자 이상이 되어야 한다
const isValidInput = userName.length >= 1 && phoneNumber.length >= 1 && address.length >= 1;

// 검사한 모든 로직의 유효성 검사가 true가 될때 getIsActive함수가 작동한다. 버튼 클릭 이벤트가 발생할때 넣어줄 함수.
const getIsActive = 
   isValidEmail && isValidPassword && isValidInput && checkBoxActive === true;

// 유효성 검사 중 하나라도 만족하지못할때 즉, 버튼이 비활성화 될 때 버튼을 클릭하면 아래와 같은 경고창이 뜬다.
const handleButtomValid = () => {
 if (
   !isValidInput ||
   !isValidEmail ||
   !isValidPassword ||
   !isCheckBoxClicked()
   ) {
   alert('please fill in the blanks');
 };
 
 // jxs
 
   <button
         className={
           getIsActive ? 'signUpButtonAction' : 'signUpButtonInaction'
         }
         type="button"
         onClick={handleButtonValid}
       >
         CREATE USER ACCOUNT
       </button>
profile
투명인간

0개의 댓글