react form 유효성 검사

해적왕·2022년 11월 20일
0

   <input
     ref={idRef}
     type="text"
     id="userId"
     name="userId"
     placeholder="아이디"
     onChange={(e) => setUserId(e.target.value)}
     style={
     errors == "아이디를 입력해주세요."
     ? { border: "1px solid red", borderRadius: "5px 5px 0 0" }
    : { borderBottom: "1px solid #eee" }
    }
/>

input은 이런식으로 만들어 주었다.

{errors && (
  <ErrMsg>
    <AiOutlineExclamationCircle style={{ margin: "1px 10px 0 0" }} />
      {errors}
  </ErrMsg>
)}
 <Button type="button" onClick={() => check()}>
  확인
 </Button>

하단에 error 메세지가 들어올 곳과 버튼.
AiOutlineExclamationCircle는 react-icons.

check()

  const check = () => {
    const data = {
      userId,
      userName,
      email,
    };

    checkValidation(data);

    if (checkValidation()) {
      getData(data);
      navigate("/send");
    }
  };

checkValidation()이 true일 때 동작하기 위함이다.

checkValidation()

  const [errors, setErrors] = useState("");
  const idRef = useRef();
  const nameRef = useRef();
  const emailRef = useRef();
  
  const checkValidation = (data) => {
    const emailRegex =
      /^(([^<>()\[\].,;:\s@"]+(\.[^<>()\[\].,;:\s@"]+)*)|(".+"))@(([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{2,})$/i;

    if (userId === "" || userId.length === 0) {
      setErrors("아이디를 입력해주세요.");
      idRef.current.focus();
      return false;
    } else if (userName === "" || userName.length === 0) {
      setErrors("이름을 입력해주세요.");
      nameRef.current.focus();
      return false;
    } else if (email != "") {
      if (!emailRegex.test(email)) {
        setErrors("이메일을 다시 입력해주세요.");
        emailRef.current.focus();
        return false;
      }
    } else if (email === "" || email.length === 0) {
      setErrors("이메일을 입력해주세요.");
      emailRef.current.focus();
      return false;
    }
    return true;
  };

early exit 패턴이라고 한다.

profile
프론트엔드

0개의 댓글