validate 动态验证 根据name值验证

这篇博客介绍了一种在不修改源文件的情况下进行表单验证的方法。通过指定input框的name值(如constraintValues),可以动态地为所有具有该name属性的input元素添加验证。文中提供了一个完整的页面示例,展示如何实现这一功能。
摘要由CSDN通过智能技术生成

直接添加验证

$('#form').validate({
        		rules:{
        			paramName:{
        				required:true
        			},
        			paramRemark:{
        				required:true
        			},
        			paramType:{
        				required:true
        			},
        			constraintValues:{
        				required:true
        			},
        			constraintCondition:{
        				required:true
        			},
        			paramAttribute:{
        				required:true
        			}
        		},
        		messsages:{
        			paramName:{
        				required:"必填项"
        			},
        			paramRemark:{
        				required:"必填项"
        			},
        			paramType:{
        				required:"必填项"
        			},
        			constraintValues:{
        				required:"必填项"
        			},
        			constraintCondition:{
        				required:"必填项"
        			},
        			paramAttribute:{
        				required:"必填项"
        			}
        		}
        	});

动态添加验证 , 用add 
$("#paramValue").rules("add",{required:true});  

if(max){
        		$("#paramValue").rules("add",{required:true, range: [min,max]});  
        	} else {
        		$("#paramValue").rules("add",{required:true});  
        	}

根据name值验证,这儿借鉴了网上的方法 点击打开链接,原作者说了两种方法,修改源文件和在当前js加判断 两种方法

这儿采用的是不修改源文件的情况下验证,首先要初始化添加一个判断

//validate  根据name验证 不修改源码
        	if ($.validator) {
   	           $.validator.prototype.elements = function () {
   	               var validator = this,
   	                 rulesCache = {};
   	 
   	               // select all valid inputs inside the form (no submit or reset buttons)
   	               return $(this.currentForm)
   	               .find("input, select, textarea")
   	               .not(":submit, :reset, :image, [disabled]")
   	               .not(this.settings.ignore)
   	               .filter(function () {
   	                   if (!this.name && validator.settings.debug && window.console) {
   	                       console.error("%o has no name assigned", this);
   	                   }
   	                   //注释这行代码
   	                   // select only the first element for each name, and only those with rules specified
   	                   //if ( this.name in rulesCache || !validator.objectLength($(this).rules()) ) {
   	                   //    return false;
   	                   //}
   	                   rulesCache[this.name] = true;
   	                   return true;
   	               });
   	           }
   	        }
添加过判断之后,就可以添加验证

其中constraintValues为form表单中input框的name值,这样就把所有name为constraintValues的input框全部添加验证

$('#form').validate({
            		rules:{
            			constraintValues:{
            				required:true
            			}
            		},
            		messages:{
            			constraintValues:{
            				required:"必填项"
            			}
            		}
            	});


顺便贴上整个页面供参考

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@include file="../../base/taglib.jsp" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<!-- Head -->
<head>
    <%@include file="../../base/headerLink.jsp" %>
    <%@include file="../../base/headerLink.jsp" %>
</head>
<!-- /Head -->
<!-- Body -->
<body>
<div class="main-container container-fluid">
    <div class="row">
        <form:form id="form" method="post" class="form-horizontal" role="form" commandName="profile">
        <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">

            <div class="widget">
                <div class="widget-body">
                    <div class="form-group" hidden="true">
                        <form:label path="sysParamId" class="col-lg-4 control-label">参数ID</form:label>
                        <div class="col-lg-4">
                            <c:if test="${profile.sysParamId!=null}">
                            	<form:input type="text" class="form-control" readonly="true" path="sysParamId"/>
                            </c:if>
                            <c:if test="${profile.sysParamId==null}">
                                <form:input type="text" class="form-control" path="sysParamId"/>
                            </c:if>
                        </div>
                    </div>
                    <div class="form-group">
                        <form:label path="paramName" class="col-lg-4 control-label">参数名称</form:label>
                        <div class="col-lg-4">
                        	<c:if test="${profile.paramName!=null}">
                        		<form:input type="text" class="form-control" readonly="true"  data-validatebox="validType:['required']" path="paramName"/>
                        	</c:if>
                        	<c:if test="${profile.paramName==null}">
                        		<form:input type="text" class="form-control" data-validatebox="validType:['required']" path="paramName"/>
                        	</c:if>
                            
                        </div>
                    </div>
                    <div class="form-group">
                        <form:label path="paramValue" class="col-lg-4 control-label">参数值</form:label>
                        <div class="col-lg-4">
                        	<c:if test="${list != null}">
                        		<form:select class="form-control" path="paramValue">
	                                <form:options items="${list}"></form:options>
                            	</form:select>
                        	</c:if>
                        	<c:if test="${list == null}">
                        		<form:input type="text" class="form-control" path="paramValue"/>
                        	</c:if>
                        	
                        </div>
                    </div>
                    <div class="form-group">
                        <form:label path="constraintValue"  class="col-lg-4 control-label">约束值</form:label>
                        <c:if test="${profile.constraintValue==null}">
	                        	<input type="button" οnclick="add()" value="添加" id="addId" hidden="true" />
                        </c:if>
                        
                        <div class="col-lg-4" id="value">
	                        <c:if test="${profile.constraintValue!=null}">
	                        	<form:input type="text" class="form-control" readonly="true" path="constraintValue"/>
	                        </c:if>
	                        <%-- <c:if test="${profile.constraintValue==null}">
	                        	<form:input type="text" class="form-control" path="constraintValue"/>
	                        </c:if> --%>
                        
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <div class="col-sm-10">
                            <button type="submit" class="btn btn-blue btn-sm">${op}</button>
                            <button type="button" οnclick="window.history.go(-1);" class="btn btn-blue btn-sm">返回
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">

            <div class="widget">
                <div class="widget-body">
	
					<div class="form-group">
                        <form:label path="paramRemark" class="col-lg-4 control-label">参数备注</form:label>
                        <div class="col-lg-4">
                        	<c:if test="${profile.paramRemark!=null}">
                        		<form:input type="text" class="form-control" readonly="true" path="paramRemark"/>
                        	</c:if>
                        	<c:if test="${profile.paramRemark==null}">
                        		<form:input type="text" class="form-control" path="paramRemark"/>
                        	</c:if>
                        </div>
                    </div>
                    <div class="form-group">
                        <form:label path="paramType" class="col-lg-4 control-label">参数类型</form:label>
                        <div class="col-lg-4">
                        	<c:if test="${profile.paramType!=null}">
                        		<form:select class="form-control" disabled="true" path="paramType">
	                                <form:option value="1">字符串</form:option>
	                                <form:option value="2">整型</form:option>
	                                <form:option value="3">日期型</form:option>
	                                <form:option value="4">浮点型</form:option>
	                            </form:select>
                        	</c:if>
                        	<c:if test="${profile.paramType==null}">
                        		<form:select class="form-control" path="paramType">
	                                <form:option value="1">字符串</form:option>
	                                <form:option value="2">整型</form:option>
	                                <form:option value="3">日期型</form:option>
	                                <form:option value="4">浮点型</form:option>
	                            </form:select>
                        	</c:if>
                            
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <form:label path="constraintCondition" class="col-lg-4 control-label">约束条件</form:label>
                        <div class="col-lg-4">
                        	<c:if test="${profile.constraintCondition!=null}">
	                        	<form:select class="form-control" disabled="true" path="constraintCondition">
	                                <form:option value="1">取值范围</form:option>
	                                <form:option value="2">特殊取值</form:option>
	                            </form:select>
	                        </c:if>
	                        <c:if test="${profile.constraintCondition==null}">
	                        	<form:select class="form-control" path="constraintCondition" id="constraintCondition">
	                                <form:option value="1">取值范围</form:option>
	                                <form:option value="2">特殊取值</form:option>
	                            </form:select>
	                        </c:if>
                        </div>
                    </div>
                    <div class="form-group">
                        <form:label path="paramAttribute" class="col-lg-4 control-label">权限</form:label>
                        <div class="col-lg-4">
                        <c:if test="${profile.paramAttribute!=null}">
                        	<form:select class="form-control" disabled="true" path="paramAttribute">
                                <form:option value="1">可见可编辑</form:option>
                                <form:option value="2">可见不可编辑</form:option>
                                <form:option value="3">不可见</form:option>
                            </form:select>
                        </c:if>
                        <c:if test="${profile.paramAttribute==null}">
                        	<form:select class="form-control" path="paramAttribute">
                                <form:option value="1">可见可编辑</form:option>
                                <form:option value="2">可见不可编辑</form:option>
                                <form:option value="3">不可见</form:option>
                            </form:select>
                        </c:if>
                            
                        </div>
                    </div>
                </div>
            </div>
        </div>
        </form:form>
    </div>
    <%@include file="../../base/footerLink.jsp" %>
    <script src="<c:url value='/static/module/JQuery zTree v3.5.15/js/jquery.ztree.all-3.5.min.js'/>"></script>
    <script src="<c:url value='/static/assets/js/validation/jquery.validate.min.js'/>"></script>
    <%-- <script src="<c:url value='/static/assets/js/validation/prototype_for_validation.js'/>"></script>
    <script src="<c:url value='/static/assets/js/validation/validation_cn.js'/>"></script> --%>
    <script>
	    var max = '${max}',
	    	min = '${min}',
	    	list = '${list}';
        $(function () {
        	//validate  根据name验证 不修改源码
        	if ($.validator) {
   	           $.validator.prototype.elements = function () {
   	               var validator = this,
   	                 rulesCache = {};
   	 
   	               // select all valid inputs inside the form (no submit or reset buttons)
   	               return $(this.currentForm)
   	               .find("input, select, textarea")
   	               .not(":submit, :reset, :image, [disabled]")
   	               .not(this.settings.ignore)
   	               .filter(function () {
   	                   if (!this.name && validator.settings.debug && window.console) {
   	                       console.error("%o has no name assigned", this);
   	                   }
   	                   //注释这行代码
   	                   // select only the first element for each name, and only those with rules specified
   	                   //if ( this.name in rulesCache || !validator.objectLength($(this).rules()) ) {
   	                   //    return false;
   	                   //}
   	                   rulesCache[this.name] = true;
   	                   return true;
   	               });
   	           }
   	        }
        	
        	//初始化验证
        	$('#form').validate({
        		rules:{
        			paramName:{
        				required:true
        			},
        			paramRemark:{
        				required:true
        			},
        			paramType:{
        				required:true
        			},
        			constraintValues:{
        				required:true
        			},
        			constraintCondition:{
        				required:true
        			},
        			paramAttribute:{
        				required:true
        			}
        		},
        		messsages:{
        			paramName:{
        				required:"必填项"
        			},
        			paramRemark:{
        				required:"必填项"
        			},
        			paramType:{
        				required:"必填项"
        			},
        			constraintValues:{
        				required:"必填项"
        			},
        			constraintCondition:{
        				required:"必填项"
        			},
        			paramAttribute:{
        				required:"必填项"
        			}
        		}
        	});
        	
        	//为参数值添加动态验证
        	if(max){
        		$("#paramValue").rules("add",{required:true, range: [min,max]});  
        	} else {
        		$("#paramValue").rules("add",{required:true});  
        	}
        	
        	//动态验证 动态添加的input输入框 根据name添加验证
        	$("#value").delegate("input","change",function(){
        		$('#form').validate({
            		rules:{
            			constraintValues:{
            				required:true
            			}
            		},
            		messages:{
            			constraintValues:{
            				required:"必填项"
            			}
            		}
            	});
        	})
        	
        	if('${op}'=='新增'){
        		add();
        		add();
        	}
        	
        	//约束条件改变时触发事件
        	$('#constraintCondition').change(function(){
        		//将已添加的input框移除掉
        		$('#value').empty();
        		if($('#constraintCondition').val()==1){//取值范围
            		$('#addId').hide();
            		add();
            		add();
            	} else if($('#constraintCondition').val()==2){//特殊取值
            		$('#addId').show();
            		add();
            	}
        	})
        })
        
        //动态添加input框
        function add(){
		    var input1 = document.createElement('input');
		    input1.setAttribute('type', 'text');
		    input1.setAttribute('name', 'constraintValues');
		    //input1.setAttribute('path', 'constraintValue');
		    input1.setAttribute('form', 'form');
		    input1.setAttribute('class', 'form-control');
		    
		    var btn1 = document.getElementById("value");
		    btn1.insertBefore(input1,null);
		}
    </script>
</body>
<!--  /Body -->
</html>





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值