jQuery Validate插件使用

這幾天一直在接觸驗證方面的工作,jQuery Validate是一個比較常用的驗證插件,說一下心得吧。

效果圖類似

說一個簡單的,現在需求是模板編號只能是正整數數字。

控件代碼如下:

<div class="control-group">
	<label class="control-label">模板編號:</label>
	<div class="controls">
		<form:input path="value" htmlEscape="false" maxlength="11"  class="input-xlarge required"/>
		<span class="help-inline"><font color="red">*</font> </span>
	</div>
</div>
接下來就是使用jQuery了,第一步肯定是導入js庫了,這個不用說,第二步開始寫js

<script type="text/javascript">
	$(document).ready(function() {
		// 模板編號驗證
		jQuery.validator.addMethod("isInteger", function(value, element) {
			var aint=parseInt(value);	
			return aint>0&& (aint+"")==value;   
		}, "請正確填寫模板編號");
		
		if($("#value")){
			$("#value").focus();
		}
		
		$("#inputForm").validate({
		    rules : {
		    	value : {
		    		isInteger : true,
		            required : true
		        }
		    },
		    messages : {
		    	value : {
		            required : "請輸入模板編號",
		            //isInteger : "請正確填寫您的模板編號"
		        }
		    },
			submitHandler: function(form){
				loading('正在提交,請稍等...');
				form.submit();
			},
			errorContainer: "#messageBox",
			errorPlacement: function(error, element) {
				$("#messageBox").text("輸入有誤,請先更正。");
				if (element.is(":checkbox")||element.is(":radio")||element.parent().is(".input-append")){
					error.appendTo(element.parent().parent());
				} else {
					error.insertAfter(element);
				}
			}
		});
	});
</script>
解釋一下吧,首先jQuery.validator.addMethod(function,String)裏寫的是自定義的驗證方法和輸出的信息;

然後if($("#value")){ $("#value").focus();}是一個聚焦的判斷;

$("#inputForm").validate()裏面就是寫規則神馬的了,inputForm值要驗證的表單ID,rules是要使用的規則,messages是輸出的信息,submitHandler是提交的時候要做什麼,errorPlacement是錯誤信息放置的地方

效果圖:

但是僅僅斯這樣肯定是不夠的,編號一般都是唯一的,所以在用戶填寫完後,還需要查重。

rules : {
	value : {
		isInteger : true,
        required : true,
            remote: {
             url: "${ctx}/portal/porTemplate/checkValue",//後臺處理程序
            type: "post",               //數據發送方式
             dataType: "json",           //接受數據格式   
            data: {                     //要傳遞的數據
            	value: function() {
                    return $("#value").val();
                 }
             }
         }
    }
},
messages : {
	value : {
        required : "請輸入模板編號",
        //isInteger : "請正確填寫您的模板編號"
        remote:"模板編號已經存在"
   	}
}

這裏使用了remote,調用url處的檢驗方法,同時把date傳進去,返回false的時候會提示messages裏面remote的信息。

查重部分如下:

@RequestMapping(value = "checkValue")
public String checkMobile(String value, Model model,
		RedirectAttributes redirectAttributes) {
	PorTemplate su = new PorTemplate();
	su.setValue(value);
	//su.getSqlMap().put("value", value);
	List<PorTemplate> list = porTemplateService.findList(su);
	if (list.size() == 0) {
		return "true";
	} else {
		return "false";
	}
}

這部分看具體情況吧,就是在數據庫裏面做個查詢。

效果圖如下:


jQuery Validate還有很多自帶的驗證方法,可以去http://www.runoob.com/jquery/jquery-plugin-validate.html學習瀏覽

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章