구현하려는 기능
회원가입 시, 누락된 부분에 대한 유효성 검사를 진행하고 해당 부분에 테두리 색이 변경되도록 구현하려고 한다.
그리고, 해당 부분에 focus가 잡히도록 할 예정이다.
유효성 검사하기
유효성 검사를 하기 위해 validation.js 라는 파일을 생성하고 그곳에서 유효성검사를 한 후, 결과값을 리턴하도록 만들었다.
export const onChangeEmail = (
value,
setHandler,
isHandler,
messageHandler,
setCheckHandler
) => {
const emailRegex = /^[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*$/i;
const emailCurrent = value;
setHandler(emailCurrent);
if (emailCurrent === '') {
messageHandler('이메일은 필수 항목 입니다.');
isHandler(false);
} else if (!emailRegex.test(emailCurrent)) {
messageHandler('이메일 형식이 올바르지 않습니다.');
isHandler(false);
setCheckHandler(false);
} else {
messageHandler('');
isHandler(true);
}
return !emailRegex.test(emailCurrent);
};
// 비밀번호(유효성)
export const onChangePassword = (value, setHandler, isHandler, messageHandler) => {
const passwordRegex = /^[a-zA-Z0-9]{8,30}$/;
const passwordCurrent = value;
setHandler(passwordCurrent);
if (passwordCurrent === '') {
messageHandler('비밀번호 입력은 필수입니다.');
isHandler(false);
} else if (!passwordRegex.test(passwordCurrent)) {
messageHandler('비밀번호는 영문, 숫자를 포함하여 8자 이상이어야 합니다');
isHandler(false);
} else {
messageHandler('');
isHandler(true);
}
return !passwordRegex.test(passwordCurrent);
};
// 비밀번호 확인(유효성)
export const onChangePasswordConfirm = (
password,
value,
setHandler,
isHandler,
messageHandler
) => {
const passwordConfirmCurrent = value;
setHandler(passwordConfirmCurrent);
if (passwordConfirmCurrent === '') {
messageHandler('비밀번호 재확인은 필수 입니다.');
isHandler(false);
} else if (password === passwordConfirmCurrent) {
messageHandler('');
isHandler(true);
} else {
messageHandler('비밀번호가 일치하지 않습니다.');
isHandler(false);
}
return !(password === passwordConfirmCurrent);
};
// 이름(유효성)
export const onChangeNickName = (value, setHandler, isHandler, messageHandler) => {
const nickNameRegex = /^[a-zA-Z가-힣0-9]{2,30}$/;
const nickNameCurrent = value;
setHandler(nickNameCurrent);
if (!nickNameRegex.test(nickNameCurrent)) {
messageHandler('2글자 이상 입력해주세요.');
isHandler(false);
} else {
messageHandler('올바른 이름 형식입니다 :)');
isHandler(true);
}
return !nickNameRegex.test(nickNameCurrent);
};
확인항목은 다음과 같다.
- Password
- Password Confirm
- Name
유효성 검사는 정규식을 통해서 진행했으며, 결과값을 리턴했다. 그리고 message의 경우 props로 받은 setState값을 이용해서 값을 전달했다.
값이 변화가 있을 때 마다 확인하기
const onValidateEmail = (e) => {
const validateEmail = onChangeEmail(
e.target.value,
setEmail,
setIsEmail,
setEmailMessage,
setEmailClick
);
setValiDate({ ...validate, email: validateEmail });
};
다음과 같이 함수를 생성하고
<StInputFrom
type="text"
placeholder="이메일"
value={email}
onChange={onValidateEmail}
borderColor={isEmail}
ref={emailRef}
/>
onChange에 값을 넣었다. 한글자 한글자 변화할때마다 해당 결과값을 즉시 보여주고 싶어서 다음과 같이 진행을 했다.
Submit을 했을 때, 오류가 있는 항목으로 focus
const emailRef = useRef(false);
const passwordRef = useRef(false);
const rePasswordRef = useRef(false);
const nickNameRef = useRef(false);
const onSubmit = (e) => {
e.preventDefault();
if (validate.email === true) {
alert('이메일을 다시 확인해 주세요.');
emailRef.current.focus();
setIsEmail(false);
} else if (validate.password === true) {
alert('비밀번호를 다시 확인해 주세요.');
passwordRef.current.focus();
setIsPassword(false);
} else if (validate.rePassword === true) {
alert('비밀번호 확인을 다시 확인해 주세요.');
rePasswordRef.current.focus();
setIsPasswordConfirm(false);
} else if (validate.nickName === true) {
alert('닉네임을 다시 확인해 주세요.');
nickNameRef.current.focus();
setIsNickName(false);
} else if (emailValidate === false) {
alert('이메일 인증을 해주세요');
} else {
//회원가입 보내기
const newUser = {
id: 8,
userEmail: email + '@' + selected,
nickname: nickName,
password: password,
confirm: passwordConfirm,
};
mutation.mutate(newUser);
navigate('/');
}
};
해당항목으로 focus를 하기위해서 DOM요소로 접근할 수 있는 Ref 를 이용해서 다음과 같이 진행했다.
유효성검사에 통과하지 못한 항목의 경우, 우선순위를 UI 위에서 아래로 확인하도록 했다. 그래서 위에서부터 틀린항목에 대해 확인을 하고, 잘못된 항목의 경우, ref.current.focus()를 이용해서 해당 항목에 대해 focus가 되도록 했다.
'프로젝트' 카테고리의 다른 글
컴포넌트 상태 관리를 어떻게 할것인지에 대해서 (전역관리) (0) | 2023.06.13 |
---|---|
aws-sdk 라이브러리를 이용해 Amazon S3에 이미지 업로드 (0) | 2023.06.13 |
첫번째 프로젝트 준비 (0) | 2023.02.07 |