개발이야기/jQuery

[jQuery] validate 사용법, 예제 (form validation)

후린개발자 2022. 11. 1.
반응형

form 입력값에 유효성을 체크하는 validation plugin

입니다. 저는 메시지를 tooltip으로 띄우기 위해
bootstrap과 같이 사용했습니다. form id를 지정하시고, form 태그 안에 name을 지정하셔서 필수 입력값에 대해서

메시지를 입력해주시면 됩니다.

form 유효성 체크가 끝나면 submitHandler 가 실행됩니다. submit 될 때 마지막 이벤트를 등록하시면 됩니다.

 

<link rel="stylesheet" type="text/css" media="screen" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.5/jquery.validate.min.js"></script>

<script>
$(document).ready(function() {  
	jQuery.validator.setDefaults({
	    focusInvalid: false,
	    focusCleanup: false, 
	    onkeyup: false,
	    onclick : false,
	    showErrors: function(errorMap, errorList) {
	        $.each(this.validElements(), function (index, element) {
	            var $element = $(element);
	            $element.removeData("title") 
	                .tooltip("destroy");
	            $element.closest('.form-group').removeClass('has-error').addClass('has-success');
	        });
	        $.each(errorList, function (index, error) {
	            var $element = $(error.element);
	            if(!$element.data('title')){
	                $element.attr("title", error.message).tooltip({trigger: 'manual'}, {selector:1}).tooltip('show'); 
	                if($element.attr("type") == "radio"){
		                var text = $element.parent().find("span").text();
		                $element.parent().find("span").remove();
		                $element.after("<span>"+text+"</span>");
	                }
	            }else if($element.data('title') != error.message){
	                $element.attr('data-original-title', error.message).data("title", error.message).tooltip('show');
	            }
	            
	            $element.closest('.form-group').removeClass('has-success').addClass('has-error');
	        });
	    },        
	});

	$("#btn_save").click(function(){
    	$("#frm_user_info").submit();
	});
	$("#frm_user_info").validate({
		rules: {
			user_name : {required: true},
			phone : {required: true},
			gender : {required: true},
			cnts : {required: true}
	        },
		messages:{
			user_name : {required: "이름을 입력해주세요."},
			phone : { required: "휴대전화번호를 선택해주세요."},
			gender : { required: "성별을 선택해주세요."},
			cnts : {required: "자기소개를 입력해주세요."}
		},
		submitHandler : function(form) {
			//이벤트가 발생되면 실행될 기능
		}
	});

});
</script>
<form class="form-horizontal" id="frm_user_info" name="frm_user_info" onsubmit="return false;">
	<fieldset style="padding-top:50px;">
		<div class="form-group">
			<label class="col-md-1 control-label">이름</label>
			<div class="col-md-4">
				<input type="text" class="form-control input-sm" name="user_name" >
			</div>
			<label class="col-md-1 control-label">휴대전화번호</label>
			<div class="col-md-4">
				<input type="text" class="form-control input-sm"  name="phone" >
			</div>
		</div>
		<div class="form-group">
			<label class="col-md-1 control-label">성별</label>
			<div class="col-md-4">
				<select class="form-control input-sm" name="gender"  >
					<option></option>
					<option value="M">남성</option>
					<option value="F">여성</option>
				</select>
			</div>
			<label class="col-md-1 control-label">별명</label>
			<div class="col-md-4">
				<input type="text" class="form-control input-sm"  name="nick" >
			</div>
		</div>
		<div class="form-group">
			<label class="col-md-1 control-label">자기소개</label>
			<div class="col-md-10">
				<textarea name="cnts" rows="7" class="form-control input-sm" style="resize:none;"></textarea>
			</div>
		</div>
		<div class="form-actions" style="float:right; padding-right:120px;">
			<button type="button" class="btn btn-info btn-sm" id="btn_save">
				<strong>저장</strong>
			</button>
		</div>
	</fieldset>
</form>

 

소스 화면

 

 

반응형

댓글

💲 추천 글