gitHub: https://github.com/leeyulgok/yulgok-page
useCheckValidation.js
import { useState, useEffect, useRef } from "react";
const useCheckValidation = (type, value) => {
const [isValid, setIsValid] = useState(true);
const [error, setError] = useState("");
const [isTouched, setIsTouched] = useState(false);
const timer = useRef(null);
useEffect(() => {
if (!isTouched) return;
if (timer.current) {
clearTimeout(timer.current);
}
timer.current = setTimeout(() => {
console.log(`Checking validation for type: ${type} and value: ${value}`);
let errorMessage = "";
let regex;
switch (type) {
case "name":
regex = /^[a-zA-Z가-힣]{2,30}$/;
errorMessage = "최대 30자, 특수문자, 숫자는 불가";
break;
case "phone":
regex = /^010\d{8}$/;
errorMessage = "숫자만 가능, 010으로 시작해야 합니다";
break;
case "email":
regex = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
errorMessage = "이메일 형식이어야 합니다";
break;
default:
regex = /.*/;
}
const checkValidity = regex.test(value);
console.log(`Validity result: ${checkValidity}`);
setIsValid(checkValidity);
if (!checkValidity) {
setError(`입력값이 잘못됐습니다. 확인해주세요. ${errorMessage}`);
} else {
setError("");
}
}, 1000);
return () => {
clearTimeout(timer.current);
};
}, [type, value, isTouched]);
const touchHandler = () => {
setIsTouched(true);
};
return { isValid, error, touchHandler };
};
export default useCheckValidation;
정규 표현식 해석
1. Name : 최소 2글자, 최대 30자, 특수문자, 숫자 불가
2. Phone : 숫자만 가능, 010으로 시작
3. Email : 이메일 형식인지 파악
유효성 검사는 백엔드에서 해야 하는 건가? 프론트엔드에서 해야 하는 건가?
유효성 검사를 백엔드에서만 진행할 경우, 사용자는 회원가입을 할 때 값을 다 입력하고 가입 버튼을 누른 후에 잘못된 값을 입력했다는 걸 확인할 수 있다.
만약 사용자가 틀린 상태로 값을 입력하고 가입버튼을 눌렀는데 그대로 회원가입이 된다면, 그 회사는 큰 결함을 갖고 있는 것이다.
본 후기는 유데미-스나이퍼팩토리 10주 완성 프로젝트캠프 학습 일지 후기로 작성 되었습니다.
#프로젝트캠프 #프로젝트캠프후기 #유데미 #스나이퍼팩토리 #웅진씽크빅 #인사이드아웃 #IT개발캠프 #개발자부트캠프 #리액트 #react #부트캠프 #리액트캠프