JavaScript

jQuery validation plugin을 이용한 form validation 처리 3

  • -
반응형

앞 포스트에서 validation plugin의 기본 사용법에 대해 알아보았다.

이번 포스트에서는 validation plugin 을 사용하면서 필요한 customization에 대해 살펴보자.

 

1. 사용자 정의 메서드의 추가

앞서 validation plugin이 다양한 validation 체크 메서드를 제공한다고 소개한바 있다.

하지만 우리는 여전히 배고프다.(적절한가? ㅠㅠ)

다행히 validate plugin은 addMethod를 이용해서 사용자 정의 메서드를 등록할 수 있게 해준다.

https://jqueryvalidation.org/jQuery.validator.addMethod/

 

jQuery.validator.addMethod() | jQuery Validation Plugin

Description: Add a custom validation method. It must consist of a name (must be a legal javascript identifier), a javascript based function and a default string message. name The name of the method used to identify it and referencing it; this must be a val

jqueryvalidation.org

 

addMethod의 사용법은 아래와 같다.

$.validator.addMethod( name, function(value, element, params){} )

/*
  name: 추가할 메서드 이름
  function: validation 처리 시 실제 동작하는 함수
    value: 사용자가 입력한 값
    element: validation이 체크되는 화면 요소
    params: rule에서 작성한 검증 값
*/

가장 핵심적인 요소는 역시 validation을 처리할 function의 작성인데 true를 반환하면 validation 통과, 그렇지 않으면 실패이다.

 

대표적으로 필요한 기능이 정규 표현식을 이용한 validation 처리 등이 있다. 아래와 같이 정규 표현식을 사용하는 메서드를 추가해보자.

$.validator.addMethod("regex", function(value, element, regexp) {
	let re = new RegExp(regexp);
	let res = re.test(value);
	console.log(res, value, regexp, re)
	return res;
});

 

다음은 정규 표현식을 이용한 validation 처리이다.

화면

<label class="input-title" for="tel">전화번호 * </label>
<input type="text" id="tel" name="tel" placeholder="010-000-0000">

스크립트

$("#myform").validate({
	rules : {
		name : {..},
		email : {..},
		tel : {
			regex : "^(010|011)[-\\s]?\\d{3,4}[-\\s]?\\d{4}$"
		}
	},
	messages : {
		name : {..},
		email : {..},
		tel : {
			regex : "전화번호 양식이 잘못되었습니다."
		}
	},
	submitHandler : function() {
	}// form 전송 이외에 ajax등 어떤 동작이 필요할 때
});

 

2. 에러 표시 위치 변경

앞서 살펴봤듯이 기본적으로 에러 메시지는 에러가 발생한 요소 뒤에 코드를 삽입해서 표시한다.

그럼 다음의 경우는 어떨까?

<p>성별을 선택해주세요.*</p>
<span>
	<input type="radio" name="gender" value="male" id="male">
	<label for="male">남성</label>
	<input type="radio" name="gender" value="female" id="female">
	<label for="male">남성</label>
</span>

 

성별을 입력받을 radio 버튼이 제공되고 반드시 선택해야 한다. 당연히 required validation이 필요한 것이다.

$("#myform").validate({
	rules : {
		name : {..},
		email : {..},
		tel : {..},
		gender : {
			required : true
		}
	},
	messages : {
		name : {..},
		email : {..},
		tel : {..},
		gender : {
			required : "성별은 필수 사항입니다."
		}
	},
	submitHandler : function() {
	}// form 전송 이외에 ajax등 어떤 동작이 필요할 때
});

 

성별을 선택하지 않고 제출해보면 생각지도 못했던 부분에서 에러 메시지를 볼 수 있다.

 

특히 radio button이나 checkbox의 경우 위 화면처럼 문제가 될 수 있다.

이 경우 다음 함수를 살펴보자.

https://jqueryvalidation.org/validate/#errorplacement

 

.validate() | jQuery Validation Plugin

Description: Validates the selected form. This method sets up event handlers for submit, focus, keyup, blur and click to trigger validation of the entire form or individual elements. Each one can be disabled, see the onxxx options (onsubmit, onfocusout, on

jqueryvalidation.org

$("#myform").validate({
	rules:{},
	messages:{},
	errorPlacement:function(error, element){},
	submitHandler:function(){}
});

// error: 에러를 표현하기 위해 추가되는 <label class="error"> 요소
// element: validation이 실패한 요소

 

위와 같이 validate 함수 내에 errorPlacement라는 속성으로 에러의 표시 위치를 변경해줄 수 있다.

errorPlacement : function(error, element) {
	if (element.is(":radio") || element.is(":checkbox")) {
		element.parent().after(error);
	} else {
		element.after(error);
	}
},

 

이제 결과를 보면 우리가 원하는 위치에 메시지가 위치한 것을 확인할 수 있다.

 

[관련글]

validation 처리 1: www.goodteacher.tistory.com/161

validation 처리 2: www.goodteacher.tistory.com/162

validation 처리 3: www.goodteacher.tistory.com/163

validation 처리 4: www.goodteacher.tistory.com/164

반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.