当前位置: 代码迷 >> Web前端 >> extend jquery validate myValidate 表单应验
  详细解决方案

extend jquery validate myValidate 表单应验

热度:597   发布时间:2012-10-25 10:58:58.0
extend jquery validate myValidate 表单验证
虽然jquery validate 已经算是很好用了,不过为了更进一步的方便应用真正实现 html和js 的隔离,我花了周末两天时间 继承jquery的validate 写了比较方便的验证,使用方法多说不宜,直接看代码吧 
 
优点 
 1 使用者直接在js里 配置自己的 验证信息和提示信息用json格式 
config.rules验证规则
config.messages 验证提示信息
config.help  获得焦点时的 tip  
2 使用者不用自己在写 div lable 或者span 程序动态生成
3 使用时 只需要#('form').myValidate(configs); 即可 非常方便
4 支持 select radio checkbox 的验证同时  支持  正整数(自然数) 验证 更多业务逻辑请自己添加验证方法




/*
 * validate 0.1
 * Copyright (c) 2010 LiboLi
 * Date: 2010-08-21
 * use this validation maybe easier to kown jQuery validation
 */

(function($){ 
	jQuery.fn.myValidation=function(options){
    // init prototype with attributes and method
		if(!options)
			options={};
		var scope=this;
		this.rules=options.rules;
		this.messages=options.messages;
		this.help=options.help;
     //init checkbox and radio with a flag
		this.configs={'checkbox':{},'radiobox':{}};
     // this method to find the span element which follow form elements  ,the default count of 50 for some OOM debuger
		this.spanNext=function(spanElement){
			var i=0
			while(spanElement.attr('tagName')!='SPAN'&&i<50){
						i++;
		        		spanElement=spanElement.next();
		        	}
		       return spanElement; 	
		}
		
    //this method 
		this.each(function(){
			//bind focus blur
			var params=["input","select"];
			for(var o in params){
				$(this).find(params[o]).bind('focus',function(e){
					var temp=scope.spanNext($(this).next())
					temp.html(this.title);
					temp.removeClass()
					temp.addClass("info");
				}).bind('blur',function(e){
					var temp=scope.spanNext($(this).next())
					if(this.title==temp.html())
		           	 	temp.html("");
		           	temp.removeClass();
		         
		           	if(temp.find('label').length==0){
		           		temp.html("...");
		           		temp.addClass("yes");
		           	}else{
		           		temp.removeClass();
		           	}
		    
				});
			}
		
			//setAttribute for form elements
	    	for (i = 0, max = this.elements.length; i < max; i++) {
	    		e = this.elements[i];
	    		eName = e.name;
	    		
	    		var errorElement=document.createElement("span");
	    		  errorElement.className="error";
	    		  errorElement.setAttribute("for",eName);
	    	
           		 if(scope.help[eName])
			      		e.title=scope.help[eName];
		    	
		    	switch(e.type){
		    		case 'checkbox':
		    			var temp=scope.configs.checkbox[eName];
		    			if(temp==null){
		    				scope.configs.checkbox[eName]=eName;
		    				e.parentNode.appendChild(errorElement);	
		    
		    			}
		    			break;
		    		case 'radio':
		    		
		    			var temp=scope.configs.radiobox[eName];
		    			if(temp==null){
		    				scope.configs.radiobox[eName]=eName;
		    				e.parentNode.appendChild(errorElement);	
		    		
		    			}
		    			break;
		    		case 'button':
		    		//	debugger
		    			break;
		    		case 'submit':
		    		//	debugger;
		    			break;
		    		case 'reset':
		    		//	debugger
		    			break;	
		    		default:
		    				e.parentNode.appendChild(errorElement);	

		    		
		    		
		    	}
            }
	    });
		
		  //validate the positive integer
		  
	    jQuery.validator.addMethod("positiveValid", function(value, element, param){
	        return this.optional(element) || /^\+?[1-9][0-9]*$/.test(value);
        });	    jQuery.validator.classRuleSettings.positiveValid={positiveValid:true,messages:{positiveValid:"Please enter a valid digits number."}}
        
	    
		var result = jQuery.extend({}, this.validate( {
		    	 messages:this.messages ,
		    	 rules:this.rules,
		        errorPlacement: function(error, element) {
		        	var tempEle=scope.spanNext(element.next());
		                tempEle.html("");
		            error.appendTo(tempEle);
		        },
		        focusCleanup: false,
		        debug: false,
		       // errorElement:'span',
		        submitHandler: function(form) {
		            form.submit();
		        }
		       }));
		      
		       if(result.valid!=null)
				return result.valid();
		
	};
	
})(jQuery);  

$("form['validate'=true]").myValidation();


html 代码 调用如下

<html> 
<head>
<script type="text/javascript" src="jquery/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="jquery/jquery.metadata.js"></script>
<script type="text/javascript" src="jquery/jquery.validate.js"></script>
<!-- <script type="text/javascript" src="<c:url value="/resource/js/common/myValidate.js"/>"></script>  #FFF2E9  -->
<script type="text/javascript" src="jquery.myValidate.js"></script>

<style type="text/css">

 .error {
    color: red;
    font-size: 12px;
    font-weight: normal;
    margin-top: 1px;
    position:float;
    background: url(images/icon-error.gif) no-repeat 20px center;
    
}
 .info {
    color: red;
    font-size: 12px;
    font-weight: normal;
    margin-top: 1px;
    background: url(images/icon-info.gif) no-repeat 2px center height:16 width(16);
}
 .yes {
    color: red;
    font-size: 12px;
    font-weight: normal;
    margin-top: 1px;
    background: url(images/icon-yes.gif) no-repeat 2px center;
}

</style>

<style type="text/css">
.tableRt {
    width: 80%;
    background-color: #C0C0C0;
    border-style: outset;
    border-color: #FFFFFF;
    float: center;
    padding: 2;
    border-width: 0
}
.tableOut {
    width: 80%;
    background-color: #DFE6EE;
    border-style: outset;
    border-color: #DFE6EE;
    float: left;
    padding: 5;
    border-width: 1
}
.tableTitleTr {
    font-family: "Verdana", "Arial";
    font-size: 14px;
    color: #FFFF00;
    background-color:#5A8ECE;
}
.active_buttonHR {
    cursor:pointer;
    background-color:#EDF1F3;
    border-top:1px solid #FFFFFF;
    border-left:1px solid #FFFFFF;
    border-bottom:1px solid #6B8896;
    border-right:1px solid #6B8896;
    font-family: "Tahoma"; color:#000000; font-size:9pt;
    line-height:100%;
    text-decoration:none;
    color:#000000;
    padding:2px 2px 2px 2px
}
/*mouse over button style*/
.active_buttonHR_mouseover {
    cursor: pointer;
    background-color:#DEE9F8;
    border-top:1px solid #BCC6CD;
    border-left:1px solid #BCC6CD;
    border-bottom:1px solid #FFFFFF;
    border-right:1px solid #FFFFFF;
    font-family: "Tahoma"; color:#0064FF; font-size:9pt;
    line-height:100%;
    text-decoration:none;
    color:#202EEA;
    padding:2px 2px 2px 2px

}


</style>
  
<script type="text/javascript">
$().ready(function(){

	var configs={};
	configs.rules={'orgId':{required:true,positiveValid:true}};
	configs.messages={'orgId':{required:"must input ",positiveValid:'please input positive'}};
	configs.help={orgId:'helpTitle'};
	configs.rules.schoolName={required:true}
	configs.messages.schoolName={required:"please select"}
	configs.help.schoolName="schoolName help";
	
	configs.rules.email={required:true,email:true}
	configs.messages.email={required:"please input email",email:'valid email'}
	configs.help.email="email help";
	
	configs.rules.sex={required:true}
	configs.messages.sex={required:"please select sex"}
	configs.help.sex="sex help";
	
	configs.rules.address={required:true}
	configs.messages.address={required:"please select address"}
	configs.help.address="address help";
	
	 $("form[validate=true]").myValidation(configs);
//	 $("#form1").myValidation(configs);
});

</script>

</head>  
<body>
    <table>
        <tr>
            <td>
                 <table align="center" border =1 width=500>   
                      <form action="" name="form1" id="form1" method="POST" validate=true>   
                         
                          <tr>   
                              <td class="tableTitleTr" align="right">orgId&nbsp;:&nbsp;</td>
                              <td>
                              <input name="orgId"  type="text"  class="text"/>
                              </td>   
                          </tr>   
                            
                          <tr>   
                              <td class="tableTitleTr" align="right">schoolName&nbsp;:&nbsp;</td>
                              <td>
                              <select name="schoolName" >
                              	<option value="" selected>select</option>
                              	<option value="1">university</option>
                              	<option value="2">collage</option>
                              </select>
                              </td>   
                          </tr>   
                          <tr>   
                              <td class="tableTitleTr" align="right">email&nbsp;:&nbsp;</td>
                              <td><input  name="email"  type="text" />
                              </td>   
                          </tr>  
                          
                           <tr>   
                              <td class="tableTitleTr" align="right">sex&nbsp;:&nbsp;</td>
                              <td>
                              <input  name="sex"  type="radio" value="1">man</input>
                              <input  name="sex"  type="radio" value="0">woman</input>
                              </td>   
                          </tr>  
                           
                           <tr>   
                              <td class="tableTitleTr" align="right">address&nbsp;:&nbsp;</td>
                              <td>
                              <input  name="address"  type="checkbox" value="1">address1</input>
                           	 	<input  name="address"  type="checkbox" value="2">address2</input>
                             
                              </td>   
                          </tr>  
                          <tr>   
                              <td class="tableTitleTr" align="right">Test&nbsp;:&nbsp;</td>
                              <td>
                              
                             <input type="text" name="text"><span class="error">xxx</span>
                             
                              </td>   
                          </tr>  
                         
                            
                          <tr>   
                              <td colspan="2" align="center" ><input class="active_buttonHR" onmouseover=javascript:this.className='active_buttonHR_mouseover' onmouseout=javascript:this.className='active_buttonHR' type="submit" value="Add" /></td>   
                          </tr>        
                      </form>   
                </table>     
            </td>
        </tr>
    </table>   
</body>  
</html>  


唉 懒得写注释了,自己看吧,哪看不懂就留言吧 哈哈 哪不懂了就先googlr下 如何写jquery插件,附件是例子 直接 本地运行 validateDemo.html便可见效果,由于哥们对css不是很熟悉 所以样式难看了点,只要稍微改下即可
欢迎提出宝贵意见  谢谢
1 楼 netskys 2010-08-23  
自己当回楼主,其实我是很不欣赏js和html分离的,毕竟 我在一个input里加上我验证规则和提示,这样看的明白,也符合完整性,比如ext的一个组件就是在一个textfield里添加了所有东西
所以之前我写过一个简单一点的用法 通过配置
$.metaData.setType('attr','validate')

<input type="" name="" validate="{required:true,messages:{required:'this is message'}}"

标注 form validate=true

这样 用户 直接 在input里配置后 什么也不用管 点击 submit 就可以实现验证 

唉 唯一不爽的是 有些 浏览器对 meta 的支持不是很好,自己的属性 有时候找不到 唉 无奈下也按照大家的分离html和js 的规则写了这个 东东 有意向的 GGs MMs 可以试下哦  
  相关解决方案