이번엔 회원가입을 만들었다.
앞선 중급 프로젝트에서는 전체 회원가입 form 을 서버에 제출하고 서버에서 validator 를 구현하여 유효성과 중복을 검사하고 리다이렉트 시켜주는 방식을 사용했었다.
하지만 이번 프로젝트에서는 꼭 만들고싶은게 있다!
회원가입 과정에서 아이디를 입력할때 실시간으로 중복검사를 실시하고 결과를 알려주는 형태다!
많은 사이트에서 사용중인 방식이고 Motivation 프로젝트에서 구현해보기로 했다.
// username 중복체크 시작
function checkUsernameDup(form) {
form.username.value = form.username.value.trim();
if ( form.username.value.length == 0 ) {
clearUsernameInputMsg();
return;
}
if ( form.username.value.length < 4 ) {
clearUsernameInputMsg();
return;
}
if ( lastCheckedUsername == form.username.value ) return;
lastCheckedUsername = form.username.value;
clearUsernameInputMsg();
fetch(
'checkUsernameDup?username=' + form.username.value
)
.then(res => res.json())
.then((rs) => {
if ( rs.success ) {
validUsername = rs.data;
}
setUsernameInputMsg(rs.success, rs.msg);
});
}
실시간으로 중복검사를 해주기 위해 fetch 함수를 포함한 function 을 만들었다.
4자 이상이 입력되었는지 유효성을 검사하는 부분도 따로 존재하기 때문에 4자 이상부터 중복검사를 실시하게 만들었다.
<input autofocus class="input input-bordered" maxlength="30" name="username" onchange="$(this).keyup();"
onkeyup="checkUsernameDupDebounce();" onpaste="setTimeoutZero(() => $(this).keyup());"
placeholder="아이디"
type="text">
<div class="mt-2 text-sm"></div>
사용자가 아이디를 입력 할 input 이다.
onkeyup 이벤트 발생 시 위에서 만든 function 을 호출하게 했다.
이에 더해서! onchange 와 onpaste 이벤트는 keyup 이벤트를 발생시켜서 마찬가지로 function 을 호출할 수 있게 했다.
아래 div 엘리먼트는 중복검사의 결과를 text 로 보여주기 위해 자리를 마련해주었다 하하!
function clearUsernameInputMsg() {
$(joinForm.username).removeClass('input-accent input-error');
$(joinForm.username).next().removeClass('text-green-400 text-red-400');
$(joinForm.username).next().empty();
}
function setUsernameInputMsg(isSuccess, msg) {
if ( isSuccess ) $(joinForm.username).addClass('input-accent');
if ( !isSuccess ) $(joinForm.username).addClass('input-error');
$(joinForm.username).next().addClass(isSuccess ? 'text-green-400' : 'text-red-400');
$(joinForm.username).next().text(msg);
}
중복검사 함수에서 호출 할 함수를 작성했다.
fetch 함수의 결과에 따라 input 의 태두리 색깔도 칠해주고, div 엘리먼트에 띄울 text 와 그 색깔도 정해주고 아주 바쁜친구다.
중복검사로직님의 고생을 덜어주고자
Lodash 라이브러리를 사용해보기로 했다.
const checkUsernameDupDebounce = _.debounce(() => checkUsernameDup(joinForm), 500);
debounce 로 래퍼함수를 만들어 0.5초의 딜레이를 걸어보았다.
0.5초 안에 새로운 입력이 들어온다면 fetch 는 날라가지 않을 것이다.
아쉽지만 0.5초안에 다음 키를 누르지못하는 독수리타법까진 배려하지 못했다... ㅠ
그래도 나름 성공적인 결과가 아닐까!
motivation 프로젝트에서 이메일 인증도 만들어 볼 생각이다.
때문에 회원가입시에 email 에 대해서도 유니크한 이메일주소를 요구해야겠다.
위의 아이디 중복검사와 똑같은 방식으로 이메일 중복검사도 만들어주자!
아주 뿌듯한 하루다!