[jquery] validation plugin 사용하기

2023. 12. 18. 17:22WEB/JAVASCRIPT

1. 기본 사용법

$('#jyForm').validate({
    rules: {
        userName: { required: true, maxlength: 20 },
        pwd: { required: true, minlength: 4, maxlength: 20 },
        email: { email: true }
    },
    messages: {
        userName: {
            required: "이름을 입력하세요.",
            maxlength: $.validator.format("이름은 최대 {0}자까지 입력가능합니다.")
        },
        pwd: {
            required: "비밀번호를 입력하세요.",
            minlength: $.validator.format("비밀번호는 최소 {0}자이상 입력가능합니다."),
            maxlength: $.validator.format("비밀번호는 최대 {0}자까지 입력가능합니다.")
        },
        email: { email: "올바른 이메일주소를 입력하세요."}
    }
});

 

2. setDefaults - hidden도 validation 처리할 수 있다.

type이 hidden인 input box는 validation을 하지 않고 넘어간다.

아래와 같은 설명에 따르면, 기본적으로 hidden을 무시한다고 되어있다. 그 말은, 다음과 같이 defaults를 초기화해주면 hidden 이어도 validation을 한다. 혹은 무시할 type을 설정할 수도 있다.

Release: Validation Plugin 1.9.0:
 "...Another change should make the setup of forms with hidden elements easier, these are now ignored by default (option “ignore” has “:hidden” now as default). In theory, this could break an existing setup. In the unlikely case that it actually does, you can fix it by setting the ignore-option to “[]” (square brackets without the quotes)."
$.validator.setDefaults({
	ignore: []
});

 

3.  errorPlacement - 에러메세지 위치 지정하기

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

 

728x90