가자공부하러!

정규식 활용 회원가입 기능(아이디 중복확인, 요소 입력확인) - JavaScript, jQuery 본문

공부/Javascript, Node.js, jQuery, Ajax

정규식 활용 회원가입 기능(아이디 중복확인, 요소 입력확인) - JavaScript, jQuery

오피스엑소더스 2019. 9. 9. 08:32

1. 목표

2. 기능

3. 소스코드


1. 목표


1. 개발환경
  > Spring Boot 2.1.7, JDK 8
2. JavaScript, jQuery, 정규식을 활용해 회원가입 기능 구현


  > 뷰 요소 : ID, 이름, 비밀번호, 비밀번호 확인, 이메일


  > 정규식 활용 뷰 요소 :

- ID : 영소문자, 영대문자, 숫자만 가능하게끔 설정. 공백 포함 불가.


- 이름 : 공백 포함 불가.


- 이메일 : 이메일 형식에 맞게끔 설정(aaa@bbbb.bbb)


2. 기능


1. ID 중복체크

  > ID 입력란에 키다운 이벤트가 발생하면 ajax 통신을 통해 중복된 아이디인지 판별

  > 중복되지 않은 아이디인 경우에만 회원가입 버튼 활성화


2. 입력요소 빈 칸 체크

  > ID, 이름, 비밀번호가 비어있는지 체크

  > 비어있지 않은 경우에만 회원가입 버튼 활성화


3. 소스코드


1. 뷰(regi.jsp)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="tiles" uri="http://tiles.apache.org/tags-tiles" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<fmt:requestEncoding value="utf-8"/>
<!DOCTYPE html>
<html>
<head>
<tiles:insertAttribute name="header"/>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="<%=request.getContextPath() %>/js/member/regi.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="signup_wrap" style="width: 70%; margin: auto; margin-top: 200px;">
<div class="card card-register mx-auto mt-5">
  <div class="card-header">
      <c:choose>
        <c:when test="${memberType == 2  }">
            교수자 회원가입
        </c:when>
        <c:otherwise>
            학생 회원가입
        </c:otherwise>
    </c:choose>    
  </div>
  <div class="card-body">
    <form id="frmRegistration" action="#" method="post">
      <div class="form-group">
        <div class="form-row">
          <div class="col-md-6">
            <div class="form-label-group">
                <label for="firstName">아이디</label>
                 <input type="text" id="inputIdInSignup" name="id" class="form-control" placeholder="아이디를 입력하세요" required="required" autofocus="autofocus">
                 <div class="valid-feedback">
                    사용 가능한 아이디입니다.
                  </div>
                 <div class="invalid-feedback">
                    사용할 수 없는 아이디입니다.
                </div>
            </div>
          </div>
          <div class="col-md-6">
            <div class="form-label-group">
                <label for="lastName">성함</label>
                  <input type="text" id="inputName" name="name" class="form-control" placeholder="성함을 입력하세요" required="required">
                  <div class="valid-feedback">
                    사용 가능한 성함입니다.
                  </div>
                 <div class="invalid-feedback">
                    사용할 수 없는 성함입니다.
                </div>
            </div>
          </div>
        </div>
      </div>
      <div class="form-group">
        <div class="form-label-group">
            <label for="inputEmail">Email 주소</label>
              <input type="email" id="inputEmailInSignup" name="email" class="form-control" placeholder="Email 주소를 입력하세요" required="required">
            <div class="valid-feedback">
                사용할 수 있는 이메일입니다.
              </div>
            <div class="invalid-feedback">
                사용할 수 없는 이메일입니다.
            </div>
        </div>
      </div>
      <div class="form-group">
        <div class="form-row">
          <div class="col-md-6">
            <div class="form-label-group">
                <label for="inputPassword">비밀번호</label>
                <input type="password" id="inputPw1InSignup" name="pw" class="form-control" placeholder="비밀번호를 입력하세요" required="required">
                <div class="valid-feedback">
                    사용 가능한 비밀번호입니다.
                  </div>
                 <div class="invalid-feedback">
                    비밀번호는 5자 이상으로 입력해주세요.
                </div>
            </div>
          </div>
          <div class="col-md-6">
            <div class="form-label-group">
                <label for="confirmPassword">비밀번호 확인</label>
                  <input type="password" id="inputPw2InSignup" class="form-control" placeholder="비밀번호를 다시 입력하세요" required="required">
                <div class="valid-feedback">
                    비밀번호가 일치합니다.
                  </div>
                 <div class="invalid-feedback">
                    두 비밀번호가 일치하지 않습니다.
                </div>
            </div>
          </div>
          <c:if test="${memberType == 2  }">
              <div class="col-md-6">
                <div class="form-label-group">
                    <label for="inputTeacherNumber">교수자 고유번호 입력</label>
                      <input type="text" id="inputTeacherNum" name="teacherNum" class="form-control" placeholder="발급받은 교수자 번호를 입력하세요" required="required">
                </div>
              </div>
          </c:if>
              <c:choose>
                <c:when test="${memberType == 2  }">
                    <input type="hidden" name="auth" value="2">
                </c:when>
                <c:otherwise>
                    <input type="hidden" name="auth" value="3">
                </c:otherwise>
            </c:choose>
        </div>
      </div>
      <input type="button" class="btn btn-primary btn-block" value="회원가입" id="btnConfirm"/>
    </form>
    
  </div>
</div>
</div>
 
</body>
</html>
cs


2. 자바스크립트(regi.js)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
/**
 * 
 */
 
$(function(){
    //context path
    var ctx = window.location.pathname.substring(0window.location.pathname.indexOf("/",2));
    
    //값 초기화. 회원가입 버튼 비활성화
    $("#btnConfirm").prop("disabled",true);
    var idOk = false;
    var pw1Ok = false;
    var pw2Ok = false;
    var nameOk = false;
    var emailOk = false;
    var isOk = false;    
    
    //정규식 활용 id 체크(영소문자+숫자 5자 이상)
    $("#inputIdInSignup").keyup(function(){    
        
        //배열 초기화
        var viewData = {};        
        var inputTxt = $("#inputIdInSignup").val();
        //data[키] = 밸류
        viewData["id"= inputTxt;
        
        var chkOnlyEngNum = /^[a-zA-Z0-9_-]{5,15}$/;
 
        if( chkOnlyEngNum.test( inputTxt ) || inputTxt.length > 4){
            //정규식 조건을 통과한 경우
            $("#signupWarn").text( ' ' );    
            //Ajax 활용 ID 중복체크, 중복이 아니면? true = 사용가능 ID            
            var varIsNotDupId = false;
            //초기값 valid 적용
            $("#inputIdInSignup").removeClass("is-invalid");
            $("#inputIdInSignup").addClass("is-valid");
            $.ajax({
                type: "POST"
                , async: false
                , contentType:'application/json'
                , url: ctx + '/regi/findid'
                , datatype: "json"
                , data: JSON.stringify(viewData)
                , success: function( data ){
 
                    if( data === '0' ){
                        //컨트롤러에서 넘어온 결과가 0인 경우 사용 가능한 아이디로 판단
                        //alert('ok data 트루라고 했다');
                        $("#inputIdInSignup").removeClass("is-invalid");
                        $("#inputIdInSignup").addClass("is-valid");
                        varIsNotDupId = true;
                        idOk = true;
                        $("#signupWarn").text( ' ' );            
                        isOk = allOk( idOk, pw1Ok, pw2Ok, nameOk, emailOk );
                        if( isOk == true ){
                            $("#btnConfirm").prop("disabled",false);
                        }
                        $("#chkAllOk").text(idOk + ', ' + pw1Ok + ', ' + pw2Ok + ', ' + nameOk + ', ' + emailOk + '마지막 idOk:' + isOk );
                    }else{
                        //중복된 ID인 경우
                        $("#inputIdInSignup").removeClass("is-valid");
                        $("#inputIdInSignup").addClass("is-invalid");
                        idOk = false;
                        $("#chkAllOk").text(idOk + ', ' + pw1Ok + ', ' + pw2Ok + ', ' + nameOk + ', ' + emailOk + '마지막 idOk:' + isOk );
                        $("#signupWarn").text( '중복된 ID입니다. 다른 ID를 입력해 주세요.' );
                        $("#btnConfirm").prop("disabled",true);
                    }
                    
                }, error: function( error ){
                    alert('error : ' + error);
                }
            });                    
        }else{
            //조건에 맞지 않는 경우
            idOk = false;
            $("#btnConfirm").prop("disabled",true);
            $("#inputIdInSignup").removeClass("is-valid");
            $("#inputIdInSignup").addClass("is-invalid");
        }
    });
    
    //이름 길이 체크. 2자~20자까지
    $("#inputName").keyup(function(){
        var inputLen = $("#inputName").val().length;
        var chkBlank = /\s/g;
        var chkResult = chkBlank.test( $("#inputName").val() );
        
        //길이에 맞지 않거나 공백이 포함되어 있는 경우
        if((inputLen < 2 || inputLen > 20|| chkResult ){            
            nameOk = false;            
            $("#btnSignupInSignupModal").prop("disabled",true);
            
            $("#inputName").removeClass("is-valid");
            $("#inputName").addClass("is-invalid");
        }else{            
            nameOk = true;
            $("#signupWarn").text( ' ' );
            isOk = allOk( idOk, pw1Ok, pw2Ok, nameOk, emailOk );
            if( isOk == true ){
                $("#btnConfirm").prop("disabled",false);
            }            
            $("#inputName").removeClass("is-invalid");
            $("#inputName").addClass("is-valid");
        }
    });
    
    //PW 길이 체크
    $("#inputPw1InSignup").keyup(function(){
        if( $("#inputPw1InSignup").val().length < 5 ){
            pw1Ok = false;
            $("#btnSignupInSignupModal").prop("disabled",true);
            $("#inputPw1InSignup").removeClass("is-valid");
            $("#inputPw1InSignup").addClass("is-invalid");
        }else{
            pw1Ok = true;
            $("#signupWarn").text( ' ' );            
            isOk = allOk( idOk, pw1Ok, pw2Ok, nameOk, emailOk );
            if( isOk == true ){
                $("#btnConfirm").prop("disabled",false);
            }
            $("#chkAllOk").text(idOk + ', ' + pw1Ok + ', ' + pw2Ok + ', ' + nameOk + ', ' + emailOk + '마지막 idOk:' + isOk );
            $("#inputPw1InSignup").removeClass("is-invalid");
            $("#inputPw1InSignup").addClass("is-valid");
        }
    });
    
    //PW 확인 체크
    $("#inputPw2InSignup").keyup(function(){
        var pw1 = $("#inputPw1InSignup").val();
        var pw2 = $("#inputPw2InSignup").val();
        if( pw1 == pw2 ){
            pw2Ok = true;            
            $("#signupWarn").text( ' ' );            
            isOk = allOk( idOk, pw1Ok, pw2Ok, nameOk, emailOk );
            if( isOk == true ){
                $("#btnConfirm").prop("disabled",false);
            }
            $("#chkAllOk").text(idOk + ', ' + pw1Ok + ', ' + pw2Ok + ', ' + nameOk + ', ' + emailOk + '마지막 idOk:' + isOk );
            $("#inputPw2InSignup").removeClass("is-invalid");
            $("#inputPw2InSignup").addClass("is-valid");
        }else{
            pw2Ok = false;
            $("#btnSignupInSignupModal").prop("disabled",true);
            $("#inputPw2InSignup").removeClass("is-valid");
            $("#inputPw2InSignup").addClass("is-invalid");
        }
    });
    
    //E-mail 체크
    $("#inputEmailInSignup").keyup(function(){
        var inputTxt = $("#inputEmailInSignup").val();
        var chkEmail = /^[a-zA-Z0-9]+@([a-zA-Z0-9]{1,10})\.([a-zA-Z]{1,10})+$/;
        if( chkEmail.test(inputTxt) ){
            emailOk = true;
            $("#signupWarn").text( ' ' );
            isOk = allOk( idOk, pw1Ok, pw2Ok, nameOk, emailOk );
            if( isOk == true ){
                $("#btnConfirm").prop("disabled",false);
            }
            //$("#chkAllOk").text(idOk + ', ' + pw1Ok + ', ' + pw2Ok + ', ' + nameOk + ', ' + emailOk);
            $("#inputEmailInSignup").removeClass("is-invalid");
            $("#inputEmailInSignup").addClass("is-valid");
        }else{
            emailOk = false;
            $("#btnSignupInSignupModal").prop("disabled",true);
            $("#inputEmailInSignup").removeClass("is-valid");
            $("#inputEmailInSignup").addClass("is-invalid");
        }
    });
    
    //회원가입 버튼 클릭 이벤트
    $("#btnConfirm").click(function(){
        $("#frmRegistration").attr("action", ctx + "/regi/insert")
        $("#frmRegistration").submit();
    });
});
 
function allOk( ok1, ok2, ok3, ok4, ok5 ){
    if( ok1 && ok2 && ok3 && ok4 && ok5 ){
        return true;
    }else{
        return false;
    }
}
cs









Comments