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学习浏览

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