jquery自定义表单验证插件
本文实例为大家分享了jquery表单验证插件,供大家参考,具体内容如下
//正则表达式 varmap=newMap(); map.put("*",/[\w\W]+/); map.put("*6-16",/^[\w\W]{6,16}$/); map.put("n",/^\d+$/); map.put("n6-16",/^\d{6,16}$/); map.put("s",/^[\u4E00-\u9FA5\uf900-\ufa2d\w\.\s]+$/); map.put("s6-16",/^[\u4E00-\u9FA5\uf900-\ufa2d\w\.\s]{6,16}$/); map.put("p",/^[0-9]{6}$/);//邮编 map.put("m",/^13[0-9]{9}$|14[0-9]{9}|15[0-9]{9}$|18[0-9]{9}$/);//手机号码 map.put("e",/^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/);//email map.put("url",/^(http|https):\/\/(\w+:\/\/)?\w+(\.\w+)+.*$/);//url地址 map.put("image",/^(http|https):\/\/.*(.JPEG|.jpeg|.JPG|.jpg|.GIF|.gif|.BMP|.bmp|.PNG|.png)$/);//图片 map.put("integer",/^[1-9]\d*$/);//大于0的正整数 map.put("hj",/(\S*?)[^>]*>.*?<\/\1>|<.*?/);//过滤html标签和javascript标签 (function($,win){ Validform={ matchReg:function(datatype){ //匹配返回正则表达式有3个比较特殊所有特殊处理一下 //这3个是因为有长度判断要动态修改正则表达式 varreg1=/^\*\d{1,}-\d{1,}$/; varreg2=/^n\d{1,}-\d{1,}$/; varreg3=/^s\d{1,}-\d{1,}$/; if(reg1.test(datatype)||reg2.test(datatype)||reg3.test(datatype)){ //把开始长度和结束长度截取出来 varindex=datatype.indexOf("-"); varnums=newArray(); nums[0]=datatype.substring(1,index); nums[1]=datatype.substring(index+1,datatype.length); //替换数字 varreg; switch(datatype.substring(0,1)){ ///^[\w\W]{6,16}$/ case"*":reg=newRegExp("^[\\w\\W]{"+nums[0]+","+nums[1]+"}$");break; case"n":reg=newRegExp("^\\d{"+nums[0]+","+nums[1]+"}$");break; case"s":reg=newRegExp("^[\\u4E00-\\u9FA5\\uf900-\\ufa2d\\w\\.\\s\\\\/]{"+nums[0]+","+nums[1]+"}$");break; } returnreg; }else{ returnmap.get(datatype); } } } })(jQuery,window); HaHaUtil={ checkFrom:function(formId){ varform=$("#"+formId)[0]; //遍历表单下面的元素 for(vari=0;i<form.length;i++){ if(!HaHaUtil.resultCheck(form[i])){ returnfalse; } } returntrue; }, resultCheck:function(obj){ vartagName=obj.tagName; switch(tagName) { case"INPUT": case"TEXTAREA": $item=$(obj); vardataType=$item.attr("dataType"); //没有验证标签就不校验了 if(dataType==null){ returntrue; }else{ //获取dataType可以有多个验证用|分割开 varreType=dataType.split("|"); //把表单值前后的空格去掉 varf_value=$item.val(); if(f_value.indexOf("")!=-1){ //说明有空格也有可能中间有空格中间有空格就不会去掉 $item.val($.trim(f_value)); } vartipId=$item.attr("tipId"); $("#"+tipId).html(""); for(vari=0;i<reType.length;i++){ //如果第一个正则是empty说明是可以没值 //如果有值在根据正则校验 if(reType[i]=="empty"){ if($item.val()==""){ //就不校验了 returntrue; break; }else{ //继续校验 continue; } } if($("."+tipId).is(":hidden")){ //如果是隐藏的菜单不校验 continue; } //获取返回的正则表达式 varreg=Validform.matchReg(reType[i]); if(!reg.test($item.val())){ //判断不通过 $("#"+tipId).html($item.attr("errormsg")); returnfalse; break; }else{ //判断通过继续校验 continue; } } returntrue; } break; //没有匹配到标签就返回false default:returntrue; } } } Array.prototype.remove=function(s){ for(vari=0;i<this.length;i++){ if(s==this[i]) this.splice(i,1); } } functionMap(){ /**存放键的数组(遍历用到)*/ this.keys=newArray(); /**存放数据*/ this.data=newObject(); /** *放入一个键值对 *@param{String}key *@param{Object}value */ this.put=function(key,value){ if(this.data[key]==null){ this.keys.push(key); } this.data[key]=value; }; /** *获取某键对应的值 *@param{String}key *@return{Object}value */ this.get=function(key){ returnthis.data[key]; }; /** *删除一个键值对 *@param{String}key */ this.remove=function(key){ this.keys.remove(key); this.data[key]=null; }; /** *遍历Map,执行处理函数 * *@param{Function}回调函数function(key,value,index){..} */ this.each=function(fn){ if(typeoffn!='function'){ return; } varlen=this.keys.length; for(vari=0;i<len;i++){ vark=this.keys[i]; fn(k,this.data[k],i); } }; /** *获取键值数组(类似Java的entrySet()) *@return键值对象{key,value}的数组 */ this.entrys=function(){ varlen=this.keys.length; varentrys=newArray(len); for(vari=0;i<len;i++){ entrys[i]={ key:this.keys[i], value:this.data[i] }; } returnentrys; }; /** *判断Map是否为空 */ this.isEmpty=function(){ returnthis.keys.length==0; }; /** *获取键值对数量 */ this.size=function(){ returnthis.keys.length; }; /** *重写toString */ this.toString=function(){ vars="{"; for(vari=0;i<this.keys.length;i++,s+=','){ vark=this.keys[i]; s+=k+"="+this.data[k]; } s+="}"; returns; }; }
这个是一个js插件保存.js引用就可以了,特点灵活可以自定义校验内容原理使用正则表达式,对于隐藏的表单不校验
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01//EN""http://www.w3.org/TR/html4/strict.dtd"> <%@includefile="/common/taglibs.jsp"%> <%@pagecontentType="text/html;charset=UTF-8"%> <%@pagepageEncoding="UTF-8"%> <html> <head> <title>新建商品</title> <scripttype="text/javascript" src="<%=request.getContextPath()%>/static/v0/scripts/commodity/common_functions.js"></script> <scripttype="text/javascript" src="<%=request.getContextPath()%>/static/v0/scripts/commodity/check_data.js"></script> <scripttype="text/javascript" src="<%=request.getContextPath()%>/static/v0/scripts/commodity/commodity_create.js"></script> <scripttype="text/javascript" src="<%=request.getContextPath()%>/static/v0/scripts/jquery/jquery.form.js"></script> <scripttype="text/javascript" src="<%=request.getContextPath()%>/static/v0/scripts/haha.js"></script> <scripttype="text/javascript" src="<%=request.getContextPath()%>/static/v0/scripts/haha_upload.js"></script> <scripttype="text/javascript"> j=1; $(function(){ updateDiscountPercentage(); $("#btn_add2").click(function(){ //varnewNode='<divid="fileSelectDiv_'+j+'"class="form-inline"><divclass="form-group">'; //newNode+='<inputid="detailImgFiles_'+j+'"name="detailImgFiles"type="file"/></div>'; //newNode+='<divclass="form-group"><inputtype="button"value="删除"onclick="delDivRow(\'fileSelectDiv_'+j+'\')"/></div><divclass="form-group">'; //newNode+='<spanid="detailImgFiles_'+j+'_span"class="sr-texthighlight"></span>'; //newNode+='</div></div>'; //$("#newUploadTd").append(newNode); varnewNode2='<divclass="form-inline"id="newImgDiv_'+j+'"><divclass="form-group">'; newNode2+='<textareadataType="empty|image|*1-500"tipId="detail_span"errormsg="请输入合法的图片链接,并小于500个字符"id="newDetailImgs"name="newDetailImgs"rows="1"cols="100"></textarea>'; newNode2+='</div><divclass="form-group"> '; newNode2+='<inputtype="button"id="btn_delOld2"value="删除"onclick="delDivRow(\'newImgDiv_'+j+'\')"></div></div>'; $("#showResultTd").append(newNode2); j=j+1; }); $("input[name='needRobert']").click(function(){ varneed=$('input:radio[name="needRobert"]:checked').val(); $("tr[name='Show']").toggle(); /*if(need==1){ $("tr[name='Show']").css('display','block'); }else{ $("tr[name='Show']").css('display','none'); }*/ }); }); </script> </head> <body> <form:formmethod="post"action="#"id="hiddenForm"name="hiddenForm"> <inputtype="hidden"name="selectedCommodityItemNo" id="selectedCommodityItemNo"value=""/> <inputtype="hidden"name="imgFileName"id="imgFileName"value=""/> </form:form> <form:formcommandName="currentCommodity"name="detailDataForm" id="detailDataForm"method="post"enctype="multipart/form-data"> <divid="errorMessage" style="color:#ff2233;font-size:14px;text-align:center;"> <c:iftest="${notemptyerrorMessage}"> <c:outvalue="${errorMessage}"/> </c:if> </div> <inputtype="hidden"name="searchFunctionEntry" id="searchFunctionEntry"value="${searchFunctionEntry}"/> <divid="content"class="yui-gmember_"> <legend>新建商品</legend> <divclass="h10px"></div> <fieldset> <divclass="form-inline"> <%--<divclass="form-group"> <inputtype="button"name="save_btn"class="btnbtn-defaulttoTop_o_degbtn_width_1"onclick="createNewAppointment();"value='<fmt:messagekey="button.save"/>'id="save_btn"/> </div>--%> <divclass="form-group"> <inputtype="button"id="return_btn"name="return_btn" class="btnbtn-default"value="返回列表" onclick="returnToSeachFunction('${searchFunctionEntry}');"/> </div> </div> </fieldset> <divclass="h10px"></div> <tableborder="0"width="100%"> <tbody> <tr> <tdwidth="20%"> <divclass="form-inline"> <divclass="form-group"> <labelfor="commodityTitle"class="sr-outer">商品标题:</label> </div> </div> </td> <tdwidth="80%"> <divclass="form-inline"> <divclass="form-group"> <form:textareapath="title"id="title"dataType="s1-50" tipId="title_span"errormsg="请输入合法字符的标题,并小于50个字符"name="title" rows="1"cols="100"/> </div> <divclass="form-group"> <spanid="title_span"class="sr-texthighlight">*</span> </div> </div> </td> </tr> <tr> <tdwidth="20%"> <divclass="form-inline"> <divclass="form-group"> <labelfor="keyword"class="sr-outer">关键字:</label> </div> </div> </td> <tdwidth="80%"> <divclass="form-inline"> <divclass="form-group"> <form:textareadataType="empty|s1-50"tipId="keyword_span" errormsg="请输入合法字符的关键字,并小于50个字符"path="keyword"id="keyword" name="keyword"rows="1"cols="100"/> </div> <divclass="form-group"> <spanid="keyword_span"class="sr-texthighlight"></span> </div> </div> </td> </tr> <tr> <tdwidth="20%"> <divclass="form-inline"> <divclass="form-group"> <labelfor="commodityType"class="sr-outer">商品分类:</label> </div> </div> </td> <tdwidth="80%"> <divclass="form-inline"> <divclass="form-group"> <form:radiobuttonpath="commodityType"id="commodityType" name="commodityType"value="0"/> 虚拟商品 <form:radiobuttonpath="commodityType"id="commodityType" name="commodityType"value="1"checked="true"/> 实体商品 </div> <divclass="form-group"> <spanid="commodityType_span"class="sr-texthighlight">*</span> </div> </div> </td> </tr> <tr> <tdwidth="20%"> <divclass="form-inline"> <divclass="form-group"> <labelfor="currencyType"class="sr-outer">货币单位:</label> </div> </div> </td> <tdwidth="80%"> <divclass="form-inline"> <divclass="form-group"> <!--<form:radiobuttonpath="currencyType"id="currencyType"name="currencyType"value="0"/>福豆 --> <form:radiobuttonpath="currencyType"id="currencyType" name="currencyType"value="1"checked="true"/> 福饼 </div> <divclass="form-group"> <spanid="commodityType_span"class="sr-texthighlight">*</span> </div> </div> </td> </tr> <tr> <tdwidth="20%"> <divclass="form-inline"> <divclass="form-group"> <labelfor="pictureLink"class="sr-outer">图片链接:<span id="preview_myCustImage_span"></span></label> </div> </div> </td> <tdwidth="80%"> <divclass="form-inline"> <divclass="form-group"> <inputtype="file"id="myCustImage"name="myCustImage" size="45"/> </div> <divclass="form-group"> <inputtype="button"value="上传图片" onclick="ajaxFileUpload('myCustImage','pictureLink')"/> </div> <divclass="form-group"> <spanid="myCustImage_span" class="sr-texthighlight"></span> </div> </div> <divclass="form-inline"> <divclass="form-group"> <form:textareadataType="image|*1-500"tipId="pictureLink_span" errormsg="请输入合法图片链接,并小于500个字符"path="pictureLink" id="pictureLink"name="pictureLink"rows="2"cols="100"/> </div> <divclass="form-group"> <spanid="pictureLink_span"class="sr-texthighlight">*</span> </div> </div> </td> </tr> <tr> <tdwidth="20%"> <divclass="form-inline"> <divclass="form-group"> <labelfor="totalQuantity"class="sr-outer">总人次:</label> </div> </div> </td> <tdwidth="80%"> <divclass="form-inline"> <divclass="form-group"> <form:inputdataType="integer"tipId="totalQuantity_span" errormsg="总人次必须为正整数"path="totalQuantity"id="totalQuantity" name="totalQuantity"class="form-control"type="text" maxlength="6"size="6"/> </div> <divclass="form-group"> <spanid="totalQuantity_span"class="sr-texthighlight">*</span> </div> </div> </td> </tr> <tr> <tdwidth="20%"> <divclass="form-inline"> <divclass="form-group"> <labelfor="unitPrice"class="sr-outer">最低购买注数:</label> </div> </div> </td> <tdwidth="80%"> <divclass="form-inline"> <divclass="form-group"> <form:radiobuttonpath="unitPrice"id="unitPrice" name="unitPrice"value="1"checked="true"/> 一元 <form:radiobuttonpath="unitPrice"id="unitPrice" name="unitPrice"value="10"/> 十元 </div> <divclass="form-group"> <spanid="unitPrice_span"class="sr-texthighlight">*</span> </div> </div> </td> </tr> <!--细节图--> <tr> <tdwidth="20%"rowspan="2">细节图:<!-- <divclass="form-inline"> <divclass="form-group"> <labelfor="detailImgs"class="sr-outer">细节图: <inputtype="button"value="全部上传"onclick="uploadDetailImgs();"/><spanid="preview_detailImgs_span"></span></label> </div> </div> --> </td> <tdwidth="80%"id="newUploadTd"> <divclass="form-inline"> <divclass="form-group"> <inputtype="file"onchange="fileUpload_onselect(this)" style="display:none;"id="detailImgFiles" name="detailImgFiles"/><inputtype="button"value="选择图片" onclick="document.getElementById('detailImgFiles').click();"/> </div> <divclass="form-group"style="margin-left:20px"> <inputtype="button"id="btn_add2"value="增加一行"/> </div> <divclass="form-group"> <spanid="detailImgFiles_0_span"class="sr-texthighlight"></span> </div> </div> </td> </tr> <tr> <tdwidth="80%"id="showResultTd"><c:forEachvar="tmpEntity" items="${currentBanner.detailImages}"varStatus="status"> <divclass="form-inline"id="oldImgDiv_${tmpEntity.index}"> <divclass="form-group"> <textareaid="oldDetailImgs"name="oldDetailImgs"rows="1" cols="100">${tmpEntity.url}</textarea> <divclass="form-group"> <inputtype="button"id="btn_delOld2"value="删除" onclick="delDivRow('oldImgDiv_${tmpEntity.index}')"> </div> </div> </div> </c:forEach> <divclass="form-inline"id="newImgDiv_0"> <divclass="form-group"> <textareaid="newDetailImgs"dataType="empty|image|*1-500" tipId="detail_span"errormsg="请输入合法的图片链接,并小于500个字符" name="newDetailImgs"rows="1"cols="100"></textarea> </div> </div></td> </tr> <tr> <td> </td> <td><spanid="detail_span"class="sr-texthighlight"></span></td> </tr> <tr> <tdwidth="20%"> <divclass="form-inline"> <divclass="form-group"> <labelfor="tags"class="sr-outer">标签:</label> </div> </div> </td> <tdwidth="80%"> <divclass="form-inline"> <c:forEachvar="tmpEntity"items="${allTagList}"> <divclass="form-group"> <label><inputtype="checkbox"id="selectedTags" name="selectedTags"value="${tmpEntity.tagId}">${tmpEntity.tagName}</label> <inputtype="hidden"name="tagName_${tmpEntity.tagId}" id="tagName_${tmpEntity.tagId}"value="${tmpEntity.tagName}"/> </div> </c:forEach> <divclass="form-group"> <spanid="tags_span"class="sr-texthighlight">*</span> </div> </div> </td> </tr> <tr> <tdwidth="20%"> <divclass="form-inline"> <divclass="form-group"> <labelfor="tags"class="sr-outer">是否需要机器人:</label> </div> </div> </td> <tdwidth="80%"> <divclass="form-inline"> <divclass="form-group"> <form:radiobuttonpath="needRobert"id="needRobert" name="needRobert"value="1"/> 是 <form:radiobuttonpath="needRobert"id="needRobert" name="needRobert"value="0"checked="true"/> 否 </div> <divclass="form-group"> <spanid="unitPrice_span"class="sr-texthighlight">*</span> </div> </div> </td> </tr> <trstyle="display:none;"name="Show"> <tdwidth="20%"> <divclass="form-inline"> <divclass="form-group"> <labelfor="tags"class="sr-outer">计划售完时间:</label> </div> </div> </td> <tdwidth="80%"> <divclass="form-inline"> <form:inputtype="number"path="planSoldTime"dataType="integer"tipId="planSoldTime_" errormsg="必须为正整数"class="planSoldTime_"min="0"max="9999"/> <divclass="form-group"> <spanid="planSoldTime_"class="sr-texthighlight">*</span> </div> </div> </td> </tr> <trstyle="display:none;"name="Show"> <tdwidth="20%"> <divclass="form-inline"> <divclass="form-group"> <labelfor="tags"class="sr-outer">最大购买次数:</label> </div> </div> </td> <tdwidth="80%"> <divclass="form-inline"> <form:inputtype="number"dataType="integer"tipId="regularTriggerTotalTimes_" errormsg="必须为正整数"class="regularTriggerTotalTimes_"path="regularTriggerTotalTimes"min="1" max="10"/> <divclass="form-group"> <spanid="regularTriggerTotalTimes_"class="sr-texthighlight">*</span> </div> </div> </td> </tr> </div> </tbody> </table> </div> </form:form> <divclass="h10px"></div> <divclass="form-inline"> <divclass="form-group"> <inputtype="button"name="save_btn"id="save_btn" class="btnbtn-defaulttoTop_o_degbtn_width_1" onclick="createNewCommodity();"value='提交并预览'/> </div> </div> </body> </html>
这个是html的用法不用考虑其他的就是html代码
functionvalidateForm1(){ varflag=HaHaUtil.checkFrom('detailDataForm'); returnflag; }
这个是from表单之前的数据校验的函数。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。