本文實例為大家分享了jquery表單驗證插件,供大家參考,具體內容如下
//正則表達式 var map = new Map(); 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個是因為有長度判斷 要動態修改正則表達式 var reg1 = /^\*\d{1,}-\d{1,}$/; var reg2 = /^n\d{1,}-\d{1,}$/; var reg3 = /^s\d{1,}-\d{1,}$/; if(reg1.test(datatype) || reg2.test(datatype) || reg3.test(datatype)){ //把開始長度和結束長度截取出來 var index = datatype.indexOf("-"); var nums =new Array(); nums[0] = datatype.substring(1,index); nums[1] = datatype.substring(index+1,datatype.length); //替換數字 var reg; switch (datatype.substring(0,1)) { ///^[\w\W]{6,16}$/ case "*": reg = new RegExp("^[\\w\\W]{"+nums[0]+","+nums[1]+"}$"); break; case "n": reg = new RegExp("^\\d{"+nums[0]+","+nums[1]+"}$"); break; case "s": reg = new RegExp("^[\\u4E00-\\u9FA5\\uf900-\\ufa2d\\w\\.\\s\\\\/]{"+nums[0]+","+nums[1]+"}$"); break; } return reg; }else{ return map.get(datatype); } } } })(jQuery,window); HaHaUtil = { checkFrom : function(formId){ var form = $("#"+formId)[0]; //遍歷表單下面的元素 for(var i=0;i<form.length;i++){ if(!HaHaUtil.resultCheck(form[i])){ return false; } } return true; }, resultCheck : function(obj){ var tagName = obj.tagName; switch(tagName) { case "INPUT": case "TEXTAREA": $item = $(obj); var dataType = $item.attr("dataType"); //沒有驗證標簽 就不校驗了 if(dataType == null){ return true; }else{ //獲取 dataType 可以有多個驗證用|分割開 var reType = dataType.split("|"); //把表單值前後的空格去掉 var f_value = $item.val(); if(f_value.indexOf(" ")!=-1){ //說明有空格 也有可能中間有空格 中間有空格就不會去掉 $item.val($.trim(f_value)); } var tipId = $item.attr("tipId"); $("#"+tipId).html(""); for(var i=0;i<reType.length;i++){ //如果第一個正則是 empty 說明是可以沒值 //如果有值 在根據正則校驗 if(reType[i] == "empty"){ if($item.val() == ""){ //就不校驗了 return true; break; }else{ //繼續校驗 continue; } } if($("."+tipId).is(":hidden")){ //如果是隱藏的菜單不校驗 continue; } //獲取返回的正則表達式 var reg = Validform.matchReg(reType[i]); if(!reg.test($item.val())){ //判斷不通過 $("#"+tipId).html($item.attr("errormsg")); return false; break; }else{ //判斷通過 繼續校驗 continue; } } return true; } break; //沒有匹配到標簽就返回false default : return true; } } } Array.prototype.remove = function(s) { for (var i = 0; i < this.length; i++) { if (s == this[i]) this.splice(i, 1); } } function Map() { /** 存放鍵的數組(遍歷用到) */ this.keys = new Array(); /** 存放數據 */ this.data = new Object(); /** * 放入一個鍵值對 * @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) { return this.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(typeof fn != 'function'){ return; } var len = this.keys.length; for(var i=0;i<len;i++){ var k = this.keys[i]; fn(k,this.data[k],i); } }; /** * 獲取鍵值數組(類似Java的entrySet()) * @return 鍵值對象{key,value}的數組 */ this.entrys = function() { var len = this.keys.length; var entrys = new Array(len); for (var i = 0; i < len; i++) { entrys[i] = { key : this.keys[i], value : this.data[i] }; } return entrys; }; /** * 判斷Map是否為空 */ this.isEmpty = function() { return this.keys.length == 0; }; /** * 獲取鍵值對數量 */ this.size = function(){ return this.keys.length; }; /** * 重寫toString */ this.toString = function(){ var s = "{"; for(var i=0;i<this.keys.length;i++,s+=','){ var k = this.keys[i]; s += k+"="+this.data[k]; } s+="}"; return s; }; }
這個是一個js插件保存.js引用就可以了,特點靈活可以自定義校驗內容原理使用正則表達式,對於隱藏的表單不校驗
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <%@ include file="/common/taglibs.jsp"%> <%@page contentType="text/html;charset=UTF-8"%> <%@page pageEncoding="UTF-8"%> <html> <head> <title>新建商品</title> <script type="text/javascript" src="<%=request.getContextPath()%>/static/v0/scripts/commodity/common_functions.js"></script> <script type="text/javascript" src="<%=request.getContextPath()%>/static/v0/scripts/commodity/check_data.js"></script> <script type="text/javascript" src="<%=request.getContextPath()%>/static/v0/scripts/commodity/commodity_create.js"></script> <script type="text/javascript" src="<%=request.getContextPath()%>/static/v0/scripts/jquery/jquery.form.js"></script> <script type="text/javascript" src="<%=request.getContextPath()%>/static/v0/scripts/haha.js"></script> <script type="text/javascript" src="<%=request.getContextPath()%>/static/v0/scripts/haha_upload.js"></script> <script type="text/javascript"> j = 1; $(function(){ updateDiscountPercentage(); $("#btn_add2").click(function(){ //var newNode='<div id="fileSelectDiv_'+j+'" class="form-inline"><div class="form-group">'; //newNode +='<input id="detailImgFiles_'+j+'" name="detailImgFiles" type="file" /></div>'; //newNode +='<div class="form-group"><input type="button" value="刪除" onclick="delDivRow(\'fileSelectDiv_'+j+'\')"/></div><div class="form-group">'; //newNode +='<span id="detailImgFiles_'+j+'_span" class="sr-text highlight"></span>'; //newNode +='</div></div>'; //$("#newUploadTd").append(newNode); var newNode2='<div class="form-inline" id="newImgDiv_'+j+'"><div class="form-group">'; newNode2+='<textarea dataType="empty|image|*1-500" tipId="detail_span" errormsg="請輸入合法的圖片鏈接,並小於500個字符" id="newDetailImgs" name="newDetailImgs" rows="1" cols="100"></textarea>'; newNode2+='</div><div class="form-group"> '; newNode2+='<input type="button" id="btn_delOld2" value="刪除" onclick="delDivRow(\'newImgDiv_'+j+'\')"></div></div>'; $("#showResultTd").append(newNode2); j = j + 1; }); $("input[name='needRobert']").click(function(){ var need=$('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:form method="post" action="#" id="hiddenForm" name="hiddenForm"> <input type="hidden" name="selectedCommodityItemNo" id="selectedCommodityItemNo" value="" /> <input type="hidden" name="imgFileName" id="imgFileName" value="" /> </form:form> <form:form commandName="currentCommodity" name="detailDataForm" id="detailDataForm" method="post" enctype="multipart/form-data"> <div id="errorMessage" style="color: #ff2233; font-size: 14px; text-align: center;"> <c:if test="${not empty errorMessage }"> <c:out value="${errorMessage }" /> </c:if> </div> <input type="hidden" name="searchFunctionEntry" id="searchFunctionEntry" value="${searchFunctionEntry}" /> <div id="content" class=" yui-g member_"> <legend>新建商品</legend> <div class="h10px"></div> <fieldset> <div class="form-inline"> <%-- <div class="form-group"> <input type="button" name="save_btn" class="btn btn-default toTop_o_deg btn_width_1" onclick="createNewAppointment();" value='<fmt:message key="button.save"/>' id="save_btn"/> </div>--%> <div class="form-group"> <input type="button" id="return_btn" name="return_btn" class="btn btn-default" value="返回列表" onclick="returnToSeachFunction('${searchFunctionEntry}');" /> </div> </div> </fieldset> <div class="h10px"></div> <table border="0" width="100%"> <tbody> <tr> <td width="20%"> <div class="form-inline"> <div class="form-group"> <label for="commodityTitle" class="sr-outer">商品標題:</label> </div> </div> </td> <td width="80%"> <div class="form-inline"> <div class="form-group"> <form:textarea path="title" id="title" dataType="s1-50" tipId="title_span" errormsg="請輸入合法字符的標題,並小於50個字符" name="title" rows="1" cols="100" /> </div> <div class="form-group"> <span id="title_span" class="sr-text highlight">*</span> </div> </div> </td> </tr> <tr> <td width="20%"> <div class="form-inline"> <div class="form-group"> <label for="keyword" class="sr-outer">關鍵字:</label> </div> </div> </td> <td width="80%"> <div class="form-inline"> <div class="form-group"> <form:textarea dataType="empty|s1-50" tipId="keyword_span" errormsg="請輸入合法字符的關鍵字,並小於50個字符" path="keyword" id="keyword" name="keyword" rows="1" cols="100" /> </div> <div class="form-group"> <span id="keyword_span" class="sr-text highlight"></span> </div> </div> </td> </tr> <tr> <td width="20%"> <div class="form-inline"> <div class="form-group"> <label for="commodityType" class="sr-outer">商品分類:</label> </div> </div> </td> <td width="80%"> <div class="form-inline"> <div class="form-group"> <form:radiobutton path="commodityType" id="commodityType" name="commodityType" value="0" /> 虛擬商品 <form:radiobutton path="commodityType" id="commodityType" name="commodityType" value="1" checked="true" /> 實體商品 </div> <div class="form-group"> <span id="commodityType_span" class="sr-text highlight">*</span> </div> </div> </td> </tr> <tr> <td width="20%"> <div class="form-inline"> <div class="form-group"> <label for="currencyType" class="sr-outer">貨幣單位:</label> </div> </div> </td> <td width="80%"> <div class="form-inline"> <div class="form-group"> <!-- <form:radiobutton path="currencyType" id="currencyType" name="currencyType" value="0"/>福豆 --> <form:radiobutton path="currencyType" id="currencyType" name="currencyType" value="1" checked="true" /> 福餅 </div> <div class="form-group"> <span id="commodityType_span" class="sr-text highlight">*</span> </div> </div> </td> </tr> <tr> <td width="20%"> <div class="form-inline"> <div class="form-group"> <label for="pictureLink" class="sr-outer">圖片鏈接:<span id="preview_myCustImage_span"></span></label> </div> </div> </td> <td width="80%"> <div class="form-inline"> <div class="form-group"> <input type="file" id="myCustImage" name="myCustImage" size="45" /> </div> <div class="form-group"> <input type="button" value="上傳圖片" onclick="ajaxFileUpload('myCustImage','pictureLink')" /> </div> <div class="form-group"> <span id="myCustImage_span" class="sr-text highlight"></span> </div> </div> <div class="form-inline"> <div class="form-group"> <form:textarea dataType="image|*1-500" tipId="pictureLink_span" errormsg="請輸入合法圖片鏈接,並小於500個字符" path="pictureLink" id="pictureLink" name="pictureLink" rows="2" cols="100" /> </div> <div class="form-group"> <span id="pictureLink_span" class="sr-text highlight">*</span> </div> </div> </td> </tr> <tr> <td width="20%"> <div class="form-inline"> <div class="form-group"> <label for="totalQuantity" class="sr-outer">總人次:</label> </div> </div> </td> <td width="80%"> <div class="form-inline"> <div class="form-group"> <form:input dataType="integer" tipId="totalQuantity_span" errormsg="總人次必須為正整數" path="totalQuantity" id="totalQuantity" name="totalQuantity" class="form-control" type="text" maxlength="6" size="6" /> </div> <div class="form-group"> <span id="totalQuantity_span" class="sr-text highlight">*</span> </div> </div> </td> </tr> <tr> <td width="20%"> <div class="form-inline"> <div class="form-group"> <label for="unitPrice" class="sr-outer">最低購買注數:</label> </div> </div> </td> <td width="80%"> <div class="form-inline"> <div class="form-group"> <form:radiobutton path="unitPrice" id="unitPrice" name="unitPrice" value="1" checked="true" /> 一元 <form:radiobutton path="unitPrice" id="unitPrice" name="unitPrice" value="10" /> 十元 </div> <div class="form-group"> <span id="unitPrice_span" class="sr-text highlight">*</span> </div> </div> </td> </tr> <!-- 細節圖 --> <tr> <td width="20%" rowspan="2">細節圖: <!-- <div class="form-inline"> <div class="form-group"> <label for="detailImgs" class="sr-outer">細節圖: <input type="button" value="全部上傳" onclick="uploadDetailImgs();" /><span id="preview_detailImgs_span"></span></label> </div> </div> --> </td> <td width="80%" id="newUploadTd"> <div class="form-inline"> <div class="form-group"> <input type="file" onchange="fileUpload_onselect(this)" style="display: none;" id="detailImgFiles" name="detailImgFiles" /> <input type="button" value="選擇圖片" onclick="document.getElementById('detailImgFiles').click();" /> </div> <div class="form-group" style="margin-left: 20px"> <input type="button" id="btn_add2" value="增加一行" /> </div> <div class="form-group"> <span id="detailImgFiles_0_span" class="sr-text highlight"></span> </div> </div> </td> </tr> <tr> <td width="80%" id="showResultTd"><c:forEach var="tmpEntity" items="${currentBanner.detailImages}" varStatus="status"> <div class="form-inline" id="oldImgDiv_${tmpEntity.index}"> <div class="form-group"> <textarea id="oldDetailImgs" name="oldDetailImgs" rows="1" cols="100">${tmpEntity.url}</textarea> <div class="form-group"> <input type="button" id="btn_delOld2" value="刪除" onclick="delDivRow('oldImgDiv_${tmpEntity.index}')"> </div> </div> </div> </c:forEach> <div class="form-inline" id="newImgDiv_0"> <div class="form-group"> <textarea id="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><span id="detail_span" class="sr-text highlight"></span></td> </tr> <tr> <td width="20%"> <div class="form-inline"> <div class="form-group"> <label for="tags" class="sr-outer">標簽:</label> </div> </div> </td> <td width="80%"> <div class="form-inline"> <c:forEach var="tmpEntity" items="${allTagList}"> <div class="form-group"> <label><input type="checkbox" id="selectedTags" name="selectedTags" value="${tmpEntity.tagId}">${tmpEntity.tagName}</label> <input type="hidden" name="tagName_${tmpEntity.tagId}" id="tagName_${tmpEntity.tagId}" value="${tmpEntity.tagName}" /> </div> </c:forEach> <div class="form-group"> <span id="tags_span" class="sr-text highlight">*</span> </div> </div> </td> </tr> <tr> <td width="20%"> <div class="form-inline"> <div class="form-group"> <label for="tags" class="sr-outer">是否需要機器人:</label> </div> </div> </td> <td width="80%"> <div class="form-inline"> <div class="form-group"> <form:radiobutton path="needRobert" id="needRobert" name="needRobert" value="1" /> 是 <form:radiobutton path="needRobert" id="needRobert" name="needRobert" value="0" checked="true" /> 否 </div> <div class="form-group"> <span id="unitPrice_span" class="sr-text highlight">*</span> </div> </div> </td> </tr> <tr style="display: none;" name="Show"> <td width="20%"> <div class="form-inline"> <div class="form-group"> <label for="tags" class="sr-outer">計劃售完時間:</label> </div> </div> </td> <td width="80%"> <div class="form-inline"> <form:input type="number" path="planSoldTime" dataType="integer" tipId="planSoldTime_" errormsg="必須為正整數" class="planSoldTime_" min="0" max="9999" /> <div class="form-group"> <span id="planSoldTime_" class="sr-text highlight">*</span> </div> </div> </td> </tr> <tr style="display: none;" name="Show"> <td width="20%"> <div class="form-inline"> <div class="form-group"> <label for="tags" class="sr-outer">最大購買次數:</label> </div> </div> </td> <td width="80%"> <div class="form-inline"> <form:input type="number" dataType="integer" tipId="regularTriggerTotalTimes_" errormsg="必須為正整數" class="regularTriggerTotalTimes_" path="regularTriggerTotalTimes" min="1" max="10" /> <div class="form-group"> <span id="regularTriggerTotalTimes_" class="sr-text highlight">*</span> </div> </div> </td> </tr> </div> </tbody> </table> </div> </form:form> <div class="h10px"></div> <div class="form-inline"> <div class="form-group"> <input type="button" name="save_btn" id="save_btn" class="btn btn-default toTop_o_deg btn_width_1" onclick="createNewCommodity();" value='提交並預覽' /> </div> </div> </body> </html>
這個是html的用法不用考慮其他的就是html代碼
function validateForm1(){ var flag=HaHaUtil.checkFrom('detailDataForm'); return flag; }
這個是from表單之前的數據校驗的函數。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持。