본문 바로가기

입력 필드 유효성 검사

codeConnection 2024. 6. 22.

상태 만들기

  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [error, setError] = useState('');
  const [isButtonDisabled, setIsButtonDisabled] = useState(true);

유효성 검사 함수 만들기

const validateEmail = (email) => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
  };

  const handleEmailChange = (e) => {
    setEmail(e.target.value);
    if (!validateEmail(e.target.value)) {
      setError('이메일 형식을 확인해주세요.');
    } else {
      setError('');
    }
  };

  const handlePasswordChange = (e) => {
    setPassword(e.target.value);
    setError('');
    if (e.target.value.length < 6) {
      setError('비밀번호는 6자리 이상으로 설정해주세요');
    } else {
      setError('');
    }
  };

  const handleConfirmPasswordChange = (e) => {
    setConfirmPassword(e.target.value);
    setError('');
    if (e.target.value.length < 6) {
      setError('비밀번호는 6자리 이상으로 설정해주세요');
    } else if (password !== e.target.value) {
      setError('비밀번호가 일치하지 않습니다');
    } else {
      setError('');
    }
  };

실시간 에러 메시지 렌더링

{password !== confirmPassword && confirmPassword && (
  <ErrorMessage>비밀번호가 일치하지 않습니다</ErrorMessage>
)}
{error && <ErrorMessage>{error}</ErrorMessage>}

유효성 검사에 따른 버튼 활성화 조건부 렌더링

  useEffect(() => {
    if (email && password && confirmPassword && !error && password === confirmPassword && validateEmail(email)) {
      setIsButtonDisabled(false);
    } else {
      setIsButtonDisabled(true);
    }
  }, [email, password, confirmPassword, error]);

 

댓글