星空网 > 软件开发 > Java

不用一行代码和一句提示语就搞定整个表单验证。

页面效果

不用一行代码和一句提示语就搞定整个表单验证。

html:

引入

<script src='/images/loading.gif' data-original="http://www.cnblogs.com//Scripts/jquery-1.10.2.js"></script>
<script src='/images/loading.gif' data-original="http://www.cnblogs.com//Scripts/Validate-1.0.1.js"></script>

不用一行代码和一句提示语就搞定整个表单验证。不用一行代码和一句提示语就搞定整个表单验证。
 1 <!DOCTYPE html> 2  3 <html ="http://www.w3.org/1999/xhtml"> 4 <head runat="server"> 5   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 6   <title></title> 7   <script src='/images/loading.gif' data-original="http://www.cnblogs.com//Scripts/jquery-1.10.2.js"></script> 8   <script src='/images/loading.gif' data-original="http://www.cnblogs.com//Scripts/Validate-1.0.1.js"></script> 9   <link href="http://www.cnblogs.com//Content/system.css" rel="stylesheet" type="text/css" /> 10   <link href="http://www.cnblogs.com//Content/metro.css" rel="stylesheet" type="text/css" /> 11 </head> 12 <body> 13   <form id="form1" runat="server"> 14     <div class="form_content"> 15       <div class="form_center_part"> 16         <div class="form_view_main"> 17           <div class="form_part"> 18             <table width="100%" border="0" cellspacing="0" cellpadding="0" class="table_part_t"> 19               <tbody> 20                 <tr> 21                   <th>长度区间:</th> 22                   <td class="graytxt1"> 23                     <asp:TextBox ID="txtNewPwd" runat="server" class="required length_2_5" /> 24                   </td> 25                 </tr> 26                 <tr> 27                   <th>必填</th> 28                   <td class="graytxt1"> 29                     <asp:TextBox ID="txtPwd" runat="server" class="required"/> 30                   </td> 31                 </tr> 32                 <tr> 33                   <th>正整数</th> 34                   <td class="graytxt1"> 35                     <asp:TextBox ID="TextBox1" runat="server" class="integer" /> 36                   </td> 37                 </tr> 38                 <tr> 39                   <th>小数</th> 40                   <td class="graytxt1"> 41                     <asp:TextBox ID="TextBox3" runat="server" class="decimal" /> 42                   </td> 43                 </tr> 44                 <tr> 45                   <th>手机</th> 46                   <td class="graytxt1"> 47                     <asp:TextBox ID="txtMobile" runat="server" class="required mobile"></asp:TextBox> 48                   </td> 49                 </tr> 50                 <tr> 51                   <th>电话</th> 52                   <td class="graytxt1"> 53                     <asp:TextBox ID="TextBox2" runat="server" class="tel"></asp:TextBox> 54                   </td> 55                 </tr> 56                 <tr> 57                   <th>单选</th> 58                   <td class="graytxt1"> 59                     <asp:RadioButtonList ID="rbtnlCode" runat="server" class="rbtn required" RepeatLayout="Flow" RepeatDirection="Horizontal"> 60                       <asp:ListItem Value="1">无</asp:ListItem> 61                       <asp:ListItem Value="2">A</asp:ListItem> 62                       <asp:ListItem Value="3">B</asp:ListItem> 63                     </asp:RadioButtonList> 64                   </td> 65                 </tr> 66                 <tr> 67                   <th>多选</th> 68                   <td class="graytxt1"> 69                     <asp:CheckBoxList ID="chklCode" runat="server" class="chk required length_2_4" RepeatLayout="Flow" RepeatDirection="Horizontal"> 70                       <asp:ListItem Value="1">A</asp:ListItem> 71                       <asp:ListItem Value="2">B</asp:ListItem> 72                       <asp:ListItem Value="3">C</asp:ListItem> 73                       <asp:ListItem Value="4">D</asp:ListItem> 74                       <asp:ListItem Value="5">E</asp:ListItem> 75                     </asp:CheckBoxList> 76                     <br /> 77                     最少选择2项但不超过4项 78                   </td> 79                 </tr> 80                 <tr> 81                   <th>多选111</th> 82                   <td class="graytxt1"> 83                     <asp:CheckBoxList ID="CheckBoxList1" runat="server" class="chk length_2_0" RepeatLayout="Flow" RepeatDirection="Horizontal"> 84                       <asp:ListItem Value="1">A</asp:ListItem> 85                       <asp:ListItem Value="2">B</asp:ListItem> 86                       <asp:ListItem Value="3">C</asp:ListItem> 87                       <asp:ListItem Value="4">D</asp:ListItem> 88                       <asp:ListItem Value="5">E</asp:ListItem> 89                     </asp:CheckBoxList> 90                     <br /> 91                     至少选择2项 92                   </td> 93                 </tr> 94                 <tr> 95                   <th>下拉</th> 96                   <td class="graytxt1"> 97                     <asp:DropDownList ID="drpCode" runat="server" class="drp required"> 98                       <asp:ListItem Value="">请选择</asp:ListItem> 99                       <asp:ListItem Value="2">A</asp:ListItem>100                       <asp:ListItem Value="3">B</asp:ListItem>101                     </asp:DropDownList>102                   </td>103                 </tr>104               </tbody>105             </table>106           </div>107           <div class="btn_center">108             <asp:Button ID="btnSubmit" runat="server" CssClass="btn_box submit" Text="提交" OnClick="btnSubmit_Click" />109             <asp:Button ID="btnSave" runat="server" CssClass="btn_box save" Text="保存" OnClick="btnSave_Click" />110           </div>111         </div>112       </div>113     </div>114   </form>115 </body>116 </html>

View Code

 

脚本:Validate-1.0.1.js

不用一行代码和一句提示语就搞定整个表单验证。不用一行代码和一句提示语就搞定整个表单验证。
 1 /// <reference path="jquery-1.10.2-vsdoc.js" /> 2 /* 3   @Name:验证 4   @Author:朱翰洲  5   @WeChat/QQ:86128281 6   @Version: 1.0.1 Beta 7   @Update:2016/10/10 8   @Desc: 将会持续更新 9    10 使用说明: 11   1)demo源码为ASP.NET 12   2)需要验证的控件加onblur="Check(this)"或onclick="Check(this)"。 13   3)Check(),可自定义提示消息,无自定义时读取默认提示,详见该函数内的注释。 14   4)页面无其他逻辑验证时,可加入Validate-?.?.?.default.js脚本文件,无需在控件中加入Check(this)。 15   5)radio、checkbox和select详见selectClass或Validate()内的注释。 16   6)文本、多选有length_?_?区间验证(至少?项)时须与控件ID命名匹配(id^=xx),否则保存时将会跳过该验证,详见SaveValidate()。 17   7)若仅需控制MaxLength建议使用MaxLength属性。 18   8)常用格式验证(.mobile,.tel,.email)需对应,需要其他验证可扩展。 19   9)若有验证格式如手机、电话等格式,将不再验证长度 20   10)css文件中的名称不得与该验证中使用的class名称冲突。 21   11)所有class可根据使用习惯更改。 22  23 class: 24   1)required:非空 25   2)onerror:标记错误 26   3)length_?_?:详见checkLength()内的注释 27   4)rbtn:radio 28   5)chk:checkbox 29   6)drp:select 30   7)mobile:手机 31   8)tel:电话 32   9)email:邮箱 33  34 */ 35  36  37 //.rbtn as RadioButtonList 38 //.chk as CheckBoxList 39 //.drp as DropDownList 40 var selectClass = ".rbtn,.chk,.drp"; 41  42 //获取验证类型class 43 function getDictTypeClass() { 44   var keys = "."; 45   $.each(dictType, function (key, val) { 46     keys += key + ",."; 47   }); 48   return keys.substring(0, keys.length - 2); 49 } 50  51 var dictType = { 52   "mobile": ["手机", /^0?(13[0-9]|15[0-9]|18[0-9]|14[57])[0-9]{8}$/], 53   "tel": ["电话", /^0\d{2,3}-?\d{7,8}$/], 54   "email": ["邮箱", /^[0-9a-z][0-9a-z\-\_\.]+@([0-9a-z][0-9a-z\-]*\.)+[a-z]{2,}$/i], 55   "integer": ["整数", /^[1-9]+[0-9]*]*$/], 56   "decimal": ["数字", /^[0-9]+.?[0-9]*$/], 57 } 58  59 $(function () { 60   $(".required").each(function () { 61     $(this).parent().append("<em>*</em>");//在必填项后添加 * 标记必填,可根据需要修改显示位置 62   }); 63   try { 64     //判断是否有Check() 65     if (jQuery.isFunction(Check)) { 66       $(selectClass).click(function () { 67         Check(this); 68       }); 69       $(getDictTypeClass() + ",.required").blur(function () { 70         Check(this); 71       }); 72       $("#btnSubmit").click(function () { 73         return SubmitValidate(); 74       }) 75       $("#btnSave").click(function () { 76         return SaveValidate(); 77       }) 78     } 79   } 80   catch (err) { 81  82   } 83 }); 84  85 function Check(par, message) { 86   var id = getId(par.id); 87   if (typeof (message) == "undefined") { 88     //未设置message 读取默认提示信息 89     message = ($(id).is(selectClass) ? "请选择" : "请输入") + $(id).parent().prev().text().trim().replace(':', '').replace(':', ''); 90   } 91   Validate(id, message); 92 } 93  94 //验证 95 function Validate(id, message) { 96   var isRequired = getIsRequired(id); 97   if ($(id).is(selectClass)) { 98     $(id).css("background", "none"); 99     //单选100     if ($(id).hasClass("rbtn")) {101       if (isRequired) {102         if (typeof ($("input:radio[name='" + replaceId(id) + "']:checked").val()) == "undefined") {103           AddError(id, message);104         } else {105           RemoveError(id);106         }107       }108     }109       //多选110     else if ($(id).hasClass("chk")) {111       var options = $("input[name^='" + replaceId(id) + "']:checked").length;//选项(数量)112       var isLength = getIsCheckLength(id);//有选项限制113       if (isLength || isRequired) {114         //必选115         if (isRequired) {116           if (options > 0) {117             //有选择项限制118             if (isLength == true) {119               checkLength(id, options, "");120               //return;121             }122             else {123               RemoveError(id);124             }125           } else {126             AddError(id, message);//未选中127           }128         }129           //非必选,但选择后有选择项限制130         else if (isLength && options > 0) {131           checkLength(id, options, "");132         }133         else {134           RemoveError(id);135         }136       }137     }138       //下拉139     else if ($(id).hasClass("drp")) {140       if (isRequired) {141         if ($(id).val() == "") {142           AddError(id, message);143         } else {144           RemoveError(id);145         }146       }147     }148   }149     //TextBox150   else {151     if ($(id).val().trim() !== "") {152       if (getIsCheckLength(id)) {153         checkLength(id, $(id).val().trim().length, "text");154       }155       else {156         checkFormat(id); //格式验证不再验证长度157       }158     } else {159       if (isRequired) {160         AddError(id, message);161       } else {162         RemoveError(id);163       }164     }165   }166 }167 //是否必填168 function getIsRequired(id) {169   return $(id).hasClass("required");170 }171 //是否验证长度172 function getIsCheckLength(id) {173   if (typeof ($(id).attr('class')) != "undefined") {174     return $(id).attr('class').indexOf('length') != "-1";175   } else {176     return "false";177   }178 }179 //验证长度 itemLength长度或选项数量。text文本其他值为多选180 function checkLength(id, itemLength, text) {181   //$(id).filter(":contains('length')")182   if (getIsCheckLength(id)) {183     var length = getClassName(id, "length");184     var min = length.split('_')[1], max = length.split('_')[2];//取出最小值和最大值185     //min为0时,取max的最大长度186     if (min == 0) {187       var tips = text == "text" ? "最大长度不超过" + max + "位字符" : "需选择" + max + "项";188       if (itemLength > max) {189         AddError(id, tips);190       }191       else {192         RemoveError(id);193       }194     }195       //max为0时,取min的最小长度196     else if (max == 0) {197       if (itemLength < min) {198         AddError(id, text == "text" ? "请输入" + (min - 1) + "位以上字符" : "至少选择" + min + "项");199       }200       else {201         RemoveError(id);202       }203     }204       //min和max大于0时,取区间205     else if (min > 0 && max > 0) {206       var tips = text == "text" ? "请输入" + min + "~" + max + "位的字符" : "需选择" + +min + "~" + max + "项";207       if (itemLength < min) {208         AddError(id, tips);209       }210       else if (itemLength > max) {211         AddError(id, tips);212       }213       else {214         RemoveError(id);215       }216     }217     else {218       RemoveError(id);219     }220   }221 }222 223 String.prototype.trim = function () {224   return this.replace(/(^\s*)|(\s*$)/g, '');225 };226 var error_icon = "<img src='/images/loading.gif' data-original=/Images/error_small.png>";227 //验证失败,添加onerror228 function AddError(id, message) {229   var spId = id.replace("#", "sp");230   $(id).addClass("onerror");231   if ($(id).nextAll("span") == undefined || $(id).nextAll("span").attr("id") !== spId) {232     if ($(id).next().html() === "*") {// 提示信息放在必填验证符号后233       $(id).next().after("<span id='" + spId + "' style='color:red'>" + error_icon + message + "</span>");234     } else {235       $(id).after("<span id='" + spId + "' style='color:red'>" + error_icon + message + "</span>");236     }237   } else {238     $("#" + spId).html(error_icon + message);239   }240 }241 //验证成功,移除onerror242 function RemoveError(id) {243   $(id).removeClass("onerror");244   $(id.replace("#", "#sp")).html("");245 }246 //删除ID中的#(参数id:#txtId)247 function replaceId(id) {248   return id.replace("#", "");249 }250 //在ID前加上#(参数id:txtId)251 function getId(id) {252   return "#" + id;253 }254 //判断className是否存在,返回className255 function getClassName(id, className) {256   var clazzs = $(id).attr('class');// 获取class 字符串257   var classIndex = clazzs.substring(clazzs.indexOf(className));//截取258   if (classIndex != "-1") {259     var last = classIndex.indexOf(" ");//判断后面是否有空格或其他样式260     return (last == -1 ? classIndex : classIndex.substring(0, last));261   }262   return "";263 }264 //验证格式(验证内容详见dictType)265 function checkFormat(id) {266   if ($(id).is(getDictTypeClass()) && $(id).val().trim() != "") {267     var clazz = getDictTypeClass().replace('.', '').split(',');268     for (var i = 0; i < clazz.length; i++) {269       if ($(id).attr('class').indexOf(clazz[i].replace('.', '')) != "-1") {270         var name = clazz[i].replace('.', '');271         if (dictType[name][1].exec($(id).val().trim())) {272           RemoveError(id)273         }274         else {275           AddError(id, dictType[name][0] + "格式错误");276         }277         break;278       }279     }280   }281   else {282     RemoveError(id);283   }284 }285 286 //提交时验证287 function SubmitValidate() {288   $(".required:input").trigger('blur');289   $(selectClass).trigger('click');290   return $(".onerror").length == 0;291 }292 //保存时验证293 function SaveValidate() {294   $(".onerror").each(function () {295     RemoveError(getId($(this).attr("id")));//移除所有验证的提示296   });297   //查找所有需要验证格式的文本,若非空,验证格式是否正确298   $(getDictTypeClass()).each(function () {299     if ($(this).val().trim() != "") {300       checkFormat(getId($(this).attr("id")));301     }302   });303   //验证区间304   $("form [id^=txt],[id^=chk]").each(function () {305     var id = $(this).attr('id');306     //文本框307     if (id.indexOf("txt") != "-1") {308       if ($(this).val().trim() != "" && getIsCheckLength(getId(id))) {309         checkLength(getId(id), $(this).val().trim().length, "text");310       }311     }312       //多选313     else {314       var options = $("input[name^='" + id + "']:checked").length;315       if (options > 0 && getIsCheckLength(getId(id))) {316         checkLength(getId(id), options, "");317       }318     }319   });320   return $(".onerror").length == 0;321 }

View Code

 




原标题:不用一行代码和一句提示语就搞定整个表单验证。

关键词:

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流