웹 기초 29강 - Ajax(keyup정규식)

Whatever·2021년 12월 7일
0

웹 기초

목록 보기
29/32

member.jsp

=> keyup으로 실시간으로 정규식검증

<%@ page language="java" contentType="text/html; charset=UTF-8" 
pageEncoding="UTF-8"%>

<!DOCTYPE html>
<html lang="kr">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
  <script src="../js/jquery.serializejson.min.js"></script>
  <script src="../js/regcheck.js"></script>
  
<style>
.ziptr:hover{
	background: lime;
}
</style>  
  
<script type="text/javascript">
$(function(){
	
	
	
	//id입력시 - id keyup
	$('#id').on('keyup', function(){ // keyup -> 입력할 때 
		idval = $('#id').val().trim();
		
		idreg = /^[a-zA-Z][a-zA-Z0-9]{3,11}$/; // [a-zA-Z]한 자리 차지해서 4~12자리
		
		if(!(idreg.test(idval))){
			$(this).css('border', '2px solid red');
			//중복검사버튼 비활성 - 속성설정 prop
			$('#idbtn').prop('disabled',true);
		}else{
			$(this).css('border', '2px solid blue');
			//중복검사버튼 활성
			$('#idbtn').prop('disabled',false);
			
		}
	});
	
	//이름 입력
	//이름 정규식 - name keyup
	$('#name').on('keyup',function(){
		nameval = $(this).val().trim();
		
		namereg = /^[가-힣]{2,5}$/;
		if(!(namereg.test(nameval))){
			$(this).css('border', '2px solid red');
			$('button:submit').prop('disabled', true);
		}else{
			$(this).css('border', '2px solid blue');
			$('button:submit').prop('disabled', false);
		}
		
	});
	
	//이메일 입력
	$('#email').on('keyup', function(){
		emailval = $(this).val().trim();
		
		emailreg = /^&/;
		if(!(emailreg.test(emailval))){
			$(this).css('border', '2px solid red');
			$('button:submit').prop('disabled', true);
		}else{
			$(this).css('border', '2px solid blue');
			$('button:submit').prop('disabled', false);
		}
	});
	
	//전화번호 입력
	$('#hp').on('keyup', function(){
		hpval = $(this).val().trim();
		
		hpreg = /^&/;
		if(!(hpreg.test(hpval))){
			$(this).css('border', '2px solid red');
			$('button:submit').prop('disabled', true);
		}else{
			$(this).css('border', '2px solid blue');
			$('button:submit').prop('disabled', false);
		}
	});
	
	//비밀번호 입력
	$('#pwd').on('keyup', function(){
		pwdval = $(this).val().trim();
		
		pwdreg = /^&/;
		if(!(pwdreg.test(pwdval))){
			$(this).css('border', '2px solid red');
			$('button:submit').prop('disabled', true);
		}else{
			$(this).css('border', '2px solid blue');
			$('button:submit').prop('disabled', false);
		}
	});
	
	/* 아이디 중복검사 */
	$('#idbtn').on('click',function(){
		idvalue = $('#id').val().trim();
		
		if(idvalue.length < 1){
			alert("아이디를 입력하세요");
			return false;
		}
		
		if(idvalue.length < 4 || idvalue.length > 12){
			alert("id는 4~12 사이");
			return false;
		}
		
		//정규식 체크 - idcheck() 호출
		if(!idcheck())return false;
		
		//정규식 체크 통과하면 서버로 전송하기
		$.ajax({
			url : '/jqpro/CheckId.do',
			data : {"id" : idvalue}, // data : "id=" + idvalue
			type : 'get',
			success : function(res){
				$('#spanid').html(res.sw).css('color', 'red');
			},
			error : function(xhr){
				alert("상태 : " + xhr.status); //404(이름,path), 500(콘솔확인), 200(json형태 - jsp페이지확인)
			},
			dataType : 'json'
		});
		
	});
	
	$('#zipbtn').on('click', function(){
		window.open("zipsearch.jsp", "우편번호찾기", "width=500 height=400"); //name or target
		
	});
	
	/* 우편번호 검색 - modal */
	/* modal창에서 검색버튼 클릭시 */
	$('#but').on('click',function(){
		dongval = $('#dong').val().trim();
		console.log(dongval);
		
		if(dongval.length < 1){
			alert("입력하세요");
			return false;
		}
		
		//서버로 전송하기
		$.ajax({
			url : "<%=request.getContextPath()%>/ZipSearch.do",
			data : {"dong" : dongval},
			type : 'post',
			success : function(res){
				str = "<table border='1'>";
				str += "<tr><td>우편번호</td>";
				str += "<td>주소</td><td>번지</td></tr>";
				$.each(res,function(i,v){
					
					str += "<tr class='ziptr'><td>"+ res[i].zipcode +"</td>";
					str += "<td>"+v.addr+"</td><td>"+v.bunji+"</td></tr>";
					
				});
				str += "</table>";
				
				$('#result').html(str);
				
			},
			error : function(xhr){
				alert("상태 : " + xhr.status);
			},
			dataType : 'json'
		});
	});
	
	$(document).on('click', '.ziptr', function(){
		//$('this td:eq(0)') => 이렇게 사용하면 안 됨
		zip = $('td:eq(0)', this).text(); //this = ziptr
		addr = $('td:eq(1)', this).text();
		
		$('#zip').val(zip);
		$('#add1').val(addr);
		
		/* //실행결과 지우기 - modal을 닫기 전에 지우기
		$('#dong').val("");
		$('#result').empty(); */
		
		$('#myModal').modal('hide'); //modal객체 닫음
		
	});
	
	//모달닫는 이벤트 - 실행결과 지우기
	 $("#myModal").on('hide.bs.modal', function(){ //모달을 닫을 때 지우기
		//실행결과 지우기
			$('#dong').val(""); //#dong에 빈 값 주기
			$('#result').empty(); // #result 비우기
	 });
	
	/* 가입 - 저장하기 */
	$('form').on('submit', function(){
		//alert("submit");
		
		// 3가지 방법으로 직렬화 가능
		console.log($('form').serialize());
		console.log($('form').serializeArray());
		console.log($('form').serializeJSON()); // 외부 script 필요
		
		
		//각 항목에 대한 정규식이 통과되면 서버로 전송
		$.ajax({
			url : '/jqpro/Insert.do',
			data : $('form').serializeArray(),
			type : 'post',
			success : function(res){
				alert(res.sw);
			},
			error : function(xhr){
				alert("상태 : " + xhr.status);
			
			},
			dataType : 'json'
		});
		
	});
	
	
});
</script>  

</head>
<body>

<div class="container">
  <h2>Horizontal form</h2>
  <form class="form-horizontal" onsubmit="return false;">
  	<div class="form-group">
      <label class="control-label col-sm-2" for="id">아이디</label>
      <div class="col-sm-2">
        <input type="text" class="form-control" id="id" placeholder="Enter id" name="mem_id">
      </div>
      <button id="idbtn" type="button" class="btn btn-danger btn-sm">중복검사</button>
      <span id="spanid"></span>
    </div>
      
      
      <div class="form-group">
      <label class="control-label col-sm-2" for="name">이름</label>
      <div class="col-sm-2">
        <input type="text" class="form-control" id="name" placeholder="Enter name" name="mem_name">
       </div>
      </div>
      
      <div class="form-group">
      <label class="control-label col-sm-2" for="bir">생년월일</label>
      <div class="col-sm-2">
        <input type="date" class="form-control" id="bir" placeholder="Enter bir" name="mem_bir">
       </div>
      </div> 
      
      
    <div class="form-group">
      <label class="control-label col-sm-2" for="email">이메일</label>
      <div class="col-sm-2">
        <input type="text" class="form-control" id="email" placeholder="Enter email" name="mem_mail">
      </div>
    </div>  
      
    
    <div class="form-group">
      <label class="control-label col-sm-2" for="pwd">비밀번호</label>
      <div class="col-sm-2">          
        <input type="password" class="form-control" id="pwd" placeholder="Enter password" name="mem_pass">
      </div>
    </div>
    
    
    <div class="form-group">
      <label class="control-label col-sm-2" for="tel">전화번호</label>
      <div class="col-sm-2">          
        <input type="text" class="form-control" id="tel" placeholder="Enter tel" name="mem_tel">
      </div>
    </div>
    
    <div class="form-group">
      <label class="control-label col-sm-2" for="zip">우편번호:</label>
      <div class="col-sm-2">          
        <input type="text" class="form-control" id="zip" placeholder="Enter zip" name="mem_zip">
      </div>
      
      <button data-toggle="modal" data-target="#myModal" type="button" class="btn btn-danger btn-sm">번호검색 modal</button>
      
    </div>
    
     <div class="form-group">
      <label class="control-label col-sm-2" for="add1">주소1</label>
      <div class="col-sm-5">          
        <input type="text" class="form-control" id="add1" placeholder="Enter add1" name="mem_add1">
      </div>
    </div>
    
     <div class="form-group">
      <label class="control-label col-sm-2" for="add2">상세주소</label>
      <div class="col-sm-5">          
        <input type="text" class="form-control" id="add2" placeholder="Enter add2" name="mem_add2">
      </div>
 	</div>
 
 	<div class="form-group">        
      <div class="col-sm-offset-2 col-sm-10">
        <button type="submit" class="btn btn-primary btn-lg">Submit</button>
      </div>
	</div>
  </form>
   
</div>


<!-- Modal -->
  <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog" >
    
      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Modal Header</h4>
        </div>
        <div class="modal-body">
            <h3>찾는 동이름을 입력하세요</h3>
			<input type="text" name="dong" id="dong">
			<button type="button" id="but">검색</button>
			<br><br>
			<div id="result"></div>	
          
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>
      
    </div>
  </div>






</body>
</html>

regcheck.js

/**
 * 
 */



//



var idcheck = function(){
	//id 정규식
	
	idreg = /^[a-zA-Z][a-zA-Z0-9]{4,12}$/;
	if( !(idreg.test(idvalue))){
		alert("id형식오류");
		return false;
	}
	return true;
};






var regcheck = function(){
	//
	namevalue = $('#name').val().trim();
	
	//공백체크
	if(namevalue.length < 1){
		alert("이름 입력하세요");
		return false;
	}
	//길이체크
	if(namevalue.length < 2 || namevalue.length > 5){
		alert("이름 2~5사이");
		return false;
	}
	//정규식
	namereg = /^[가-힣]{2,5}$/;
	if(!(namereg.test(namevalue))){
		alert("이름 형식오류");
		return false;
	}
	
	//비밀번호 - 공백, 길이, 정규식
	//전화번호 - 공백, 정규식
	//이메일 - 공백, 정규식
	
	//모두 통과하면 true
	
	return true;
	
	
	
	
};

Insert.java

package kr.or.ddit.join.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kr.or.ddit.join.service.IJoinService;
import kr.or.ddit.join.service.JoinServiceImpl;
import kr.or.ddit.join.vo.MemVO;

import org.apache.commons.beanutils.BeanUtils;

@WebServlet("/Insert.do")
public class Insert extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		
		//0. 클라이언트 요청시 전송 데이터 - mem_id, mem_name, mem_add1, mem_add2,
		//mem_bir, mem_hp, mem_zip, mem_pass, mem_mail
		//한꺼번에 가져와서 MemVO에 저장
		MemVO vo = new MemVO();
		
		try {
			BeanUtils.populate(vo, request.getParameterMap());
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//1. service객체 얻기 
		IJoinService service = JoinServiceImpl.getInstance();
		
		//2. service메소드 호출 - 결과값 받기 
		String id = service.insertMember(vo);
		
		/*response.setCharacterEncoding("utf-8"); - 이렇게 할 수 있음(jsp로 전송하지 않을거면)
		PrintWriter out = response.getWriter();
		
		if(id!=null){
			out.append(" { ");
					
		}else{
			
			
		}*/
		
		//3. request에 결과값 저장
		request.setAttribute("id",id);
		
		//4. jsp로 
		request.getRequestDispatcher("1204/insert.jsp").forward(request, response);
		
		
		
	}

}

0개의 댓글