輕松搞定js表單驗(yàn)證
先看看效果圖:
html:
引入
<script src="/Scripts/jquery-1.10.2.js"></script>
<script src="/Scripts/Validate-1.0.1.js"></script>
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <script src="/Scripts/jquery-1.10.2.js"></script> <script src="/Scripts/Validate-1.0.1.js"></script> <link href="/Content/system.css" rel="stylesheet" type="text/css" /> <link href="/Content/metro.css" rel="stylesheet" type="text/css" /> </head> <body> <form id="form1" runat="server"> <div class="form_content"> <div class="form_center_part"> <div class="form_view_main"> <div class="form_part"> <table width="100%" border="0" cellspacing="0" cellpadding="0" class="table_part_t"> <tbody> <tr> <th>長(zhǎng)度區(qū)間:</th> <td class="graytxt1"> <asp:TextBox ID="txtNewPwd" runat="server" class="required length_2_5" /> </td> </tr> <tr> <th>必填</th> <td class="graytxt1"> <asp:TextBox ID="txtPwd" runat="server" class="required"/> </td> </tr> <tr> <th>正整數(shù)</th> <td class="graytxt1"> <asp:TextBox ID="TextBox1" runat="server" class="integer" /> </td> </tr> <tr> <th>小數(shù)</th> <td class="graytxt1"> <asp:TextBox ID="TextBox3" runat="server" class="decimal" /> </td> </tr> <tr> <th>手機(jī)</th> <td class="graytxt1"> <asp:TextBox ID="txtMobile" runat="server" class="required mobile"></asp:TextBox> </td> </tr> <tr> <th>電話</th> <td class="graytxt1"> <asp:TextBox ID="TextBox2" runat="server" class="tel"></asp:TextBox> </td> </tr> <tr> <th>單選</th> <td class="graytxt1"> <asp:RadioButtonList ID="rbtnlCode" runat="server" class="rbtn required" RepeatLayout="Flow" RepeatDirection="Horizontal"> <asp:ListItem Value="1">無(wú)</asp:ListItem> <asp:ListItem Value="2">A</asp:ListItem> <asp:ListItem Value="3">B</asp:ListItem> </asp:RadioButtonList> </td> </tr> <tr> <th>多選</th> <td class="graytxt1"> <asp:CheckBoxList ID="chklCode" runat="server" class="chk required length_2_4" RepeatLayout="Flow" RepeatDirection="Horizontal"> <asp:ListItem Value="1">A</asp:ListItem> <asp:ListItem Value="2">B</asp:ListItem> <asp:ListItem Value="3">C</asp:ListItem> <asp:ListItem Value="4">D</asp:ListItem> <asp:ListItem Value="5">E</asp:ListItem> </asp:CheckBoxList> <br /> 最少選擇2項(xiàng)但不超過(guò)4項(xiàng) </td> </tr> <tr> <th>多選111</th> <td class="graytxt1"> <asp:CheckBoxList ID="CheckBoxList1" runat="server" class="chk length_2_0" RepeatLayout="Flow" RepeatDirection="Horizontal"> <asp:ListItem Value="1">A</asp:ListItem> <asp:ListItem Value="2">B</asp:ListItem> <asp:ListItem Value="3">C</asp:ListItem> <asp:ListItem Value="4">D</asp:ListItem> <asp:ListItem Value="5">E</asp:ListItem> </asp:CheckBoxList> <br /> 至少選擇2項(xiàng) </td> </tr> <tr> <th>下拉</th> <td class="graytxt1"> <asp:DropDownList ID="drpCode" runat="server" class="drp required"> <asp:ListItem Value="">請(qǐng)選擇</asp:ListItem> <asp:ListItem Value="2">A</asp:ListItem> <asp:ListItem Value="3">B</asp:ListItem> </asp:DropDownList> </td> </tr> </tbody> </table> </div> <div class="btn_center"> <asp:Button ID="btnSubmit" runat="server" CssClass="btn_box submit" Text="提交" OnClick="btnSubmit_Click" /> <asp:Button ID="btnSave" runat="server" CssClass="btn_box save" Text="保存" OnClick="btnSave_Click" /> </div> </div> </div> </div> </form> </body> </html>
腳本:Validate-1.0.1.js
/// <reference path="jquery-1.10.2-vsdoc.js" /> /* @Name:驗(yàn)證 @Author:朱翰洲 @WeChat/QQ:86128281 @Version: 1.0.1 Beta @Update:2016/10/10 @Desc: 將會(huì)持續(xù)更新 使用說(shuō)明: 1)demo源碼為ASP.NET 2)需要驗(yàn)證的控件加onblur="Check(this)"或onclick="Check(this)"。 3)Check(),可自定義提示消息,無(wú)自定義時(shí)讀取默認(rèn)提示,詳見(jiàn)該函數(shù)內(nèi)的注釋。 4)頁(yè)面無(wú)其他邏輯驗(yàn)證時(shí),可加入Validate-?.?.?.default.js腳本文件,無(wú)需在控件中加入Check(this)。 5)radio、checkbox和select詳見(jiàn)selectClass或Validate()內(nèi)的注釋。 6)文本、多選有l(wèi)ength_?_?區(qū)間驗(yàn)證(至少?項(xiàng))時(shí)須與控件ID命名匹配(id^=xx),否則保存時(shí)將會(huì)跳過(guò)該驗(yàn)證,詳見(jiàn)SaveValidate()。 7)若僅需控制MaxLength建議使用MaxLength屬性。 8)常用格式驗(yàn)證(.mobile,.tel,.email)需對(duì)應(yīng),需要其他驗(yàn)證可擴(kuò)展。 9)若有驗(yàn)證格式如手機(jī)、電話等格式,將不再驗(yàn)證長(zhǎng)度 10)css文件中的名稱不得與該驗(yàn)證中使用的class名稱沖突。 11)所有class可根據(jù)使用習(xí)慣更改。 class: 1)required:非空 2)onerror:標(biāo)記錯(cuò)誤 3)length_?_?:詳見(jiàn)checkLength()內(nèi)的注釋 4)rbtn:radio 5)chk:checkbox 6)drp:select 7)mobile:手機(jī) 8)tel:電話 9)email:郵箱 */ //.rbtn as RadioButtonList //.chk as CheckBoxList //.drp as DropDownList var selectClass = ".rbtn,.chk,.drp"; //獲取驗(yàn)證類型class function getDictTypeClass() { var keys = "."; $.each(dictType, function (key, val) { keys += key + ",."; }); return keys.substring(0, keys.length - 2); } var dictType = { "mobile": ["手機(jī)", /^0?(13[0-9]|15[0-9]|18[0-9]|14[57])[0-9]{8}$/], "tel": ["電話", /^0\d{2,3}-?\d{7,8}$/], "email": ["郵箱", /^[0-9a-z][0-9a-z\-\_\.]+@([0-9a-z][0-9a-z\-]*\.)+[a-z]{2,}$/i], "integer": ["整數(shù)", /^[1-9]+[0-9]*]*$/], "decimal": ["數(shù)字", /^[0-9]+.?[0-9]*$/], } $(function () { $(".required").each(function () { $(this).parent().append("<em>*</em>");//在必填項(xiàng)后添加 * 標(biāo)記必填,可根據(jù)需要修改顯示位置 }); try { //判斷是否有Check() if (jQuery.isFunction(Check)) { $(selectClass).click(function () { Check(this); }); $(getDictTypeClass() + ",.required").blur(function () { Check(this); }); $("#btnSubmit").click(function () { return SubmitValidate(); }) $("#btnSave").click(function () { return SaveValidate(); }) } } catch (err) { } }); function Check(par, message) { var id = getId(par.id); if (typeof (message) == "undefined") { //未設(shè)置message 讀取默認(rèn)提示信息 message = ($(id).is(selectClass) ? "請(qǐng)選擇" : "請(qǐng)輸入") + $(id).parent().prev().text().trim().replace(':', '').replace(':', ''); } Validate(id, message); } //驗(yàn)證 function Validate(id, message) { var isRequired = getIsRequired(id); if ($(id).is(selectClass)) { $(id).css("background", "none"); //單選 if ($(id).hasClass("rbtn")) { if (isRequired) { if (typeof ($("input:radio[name='" + replaceId(id) + "']:checked").val()) == "undefined") { AddError(id, message); } else { RemoveError(id); } } } //多選 else if ($(id).hasClass("chk")) { var options = $("input[name^='" + replaceId(id) + "']:checked").length;//選項(xiàng)(數(shù)量) var isLength = getIsCheckLength(id);//有選項(xiàng)限制 if (isLength || isRequired) { //必選 if (isRequired) { if (options > 0) { //有選擇項(xiàng)限制 if (isLength == true) { checkLength(id, options, ""); //return; } else { RemoveError(id); } } else { AddError(id, message);//未選中 } } //非必選,但選擇后有選擇項(xiàng)限制 else if (isLength && options > 0) { checkLength(id, options, ""); } else { RemoveError(id); } } } //下拉 else if ($(id).hasClass("drp")) { if (isRequired) { if ($(id).val() == "") { AddError(id, message); } else { RemoveError(id); } } } } //TextBox else { if ($(id).val().trim() !== "") { if (getIsCheckLength(id)) { checkLength(id, $(id).val().trim().length, "text"); } else { checkFormat(id); //格式驗(yàn)證不再驗(yàn)證長(zhǎng)度 } } else { if (isRequired) { AddError(id, message); } else { RemoveError(id); } } } } //是否必填 function getIsRequired(id) { return $(id).hasClass("required"); } //是否驗(yàn)證長(zhǎng)度 function getIsCheckLength(id) { if (typeof ($(id).attr('class')) != "undefined") { return $(id).attr('class').indexOf('length') != "-1"; } else { return "false"; } } //驗(yàn)證長(zhǎng)度 itemLength長(zhǎng)度或選項(xiàng)數(shù)量。text文本其他值為多選 function checkLength(id, itemLength, text) { //$(id).filter(":contains('length')") if (getIsCheckLength(id)) { var length = getClassName(id, "length"); var min = length.split('_')[1], max = length.split('_')[2];//取出最小值和最大值 //min為0時(shí),取max的最大長(zhǎng)度 if (min == 0) { var tips = text == "text" ? "最大長(zhǎng)度不超過(guò)" + max + "位字符" : "需選擇" + max + "項(xiàng)"; if (itemLength > max) { AddError(id, tips); } else { RemoveError(id); } } //max為0時(shí),取min的最小長(zhǎng)度 else if (max == 0) { if (itemLength < min) { AddError(id, text == "text" ? "請(qǐng)輸入" + (min - 1) + "位以上字符" : "至少選擇" + min + "項(xiàng)"); } else { RemoveError(id); } } //min和max大于0時(shí),取區(qū)間 else if (min > 0 && max > 0) { var tips = text == "text" ? "請(qǐng)輸入" + min + "~" + max + "位的字符" : "需選擇" + +min + "~" + max + "項(xiàng)"; if (itemLength < min) { AddError(id, tips); } else if (itemLength > max) { AddError(id, tips); } else { RemoveError(id); } } else { RemoveError(id); } } } String.prototype.trim = function () { return this.replace(/(^\s*)|(\s*$)/g, ''); }; var error_icon = "<img src=/Images/error_small.png>"; //驗(yàn)證失敗,添加onerror function AddError(id, message) { var spId = id.replace("#", "sp"); $(id).addClass("onerror"); if ($(id).nextAll("span") == undefined || $(id).nextAll("span").attr("id") !== spId) { if ($(id).next().html() === "*") {// 提示信息放在必填驗(yàn)證符號(hào)后 $(id).next().after("<span id='" + spId + "' style='color:red'>" + error_icon + message + "</span>"); } else { $(id).after("<span id='" + spId + "' style='color:red'>" + error_icon + message + "</span>"); } } else { $("#" + spId).html(error_icon + message); } } //驗(yàn)證成功,移除onerror function RemoveError(id) { $(id).removeClass("onerror"); $(id.replace("#", "#sp")).html(""); } //刪除ID中的#(參數(shù)id:#txtId) function replaceId(id) { return id.replace("#", ""); } //在ID前加上#(參數(shù)id:txtId) function getId(id) { return "#" + id; } //判斷className是否存在,返回className function getClassName(id, className) { var clazzs = $(id).attr('class');// 獲取class 字符串 var classIndex = clazzs.substring(clazzs.indexOf(className));//截取 if (classIndex != "-1") { var last = classIndex.indexOf(" ");//判斷后面是否有空格或其他樣式 return (last == -1 ? classIndex : classIndex.substring(0, last)); } return ""; } //驗(yàn)證格式(驗(yàn)證內(nèi)容詳見(jiàn)dictType) function checkFormat(id) { if ($(id).is(getDictTypeClass()) && $(id).val().trim() != "") { var clazz = getDictTypeClass().replace('.', '').split(','); for (var i = 0; i < clazz.length; i++) { if ($(id).attr('class').indexOf(clazz[i].replace('.', '')) != "-1") { var name = clazz[i].replace('.', ''); if (dictType[name][1].exec($(id).val().trim())) { RemoveError(id) } else { AddError(id, dictType[name][0] + "格式錯(cuò)誤"); } break; } } } else { RemoveError(id); } } //提交時(shí)驗(yàn)證 function SubmitValidate() { $(".required:input").trigger('blur'); $(selectClass).trigger('click'); return $(".onerror").length == 0; } //保存時(shí)驗(yàn)證 function SaveValidate() { $(".onerror").each(function () { RemoveError(getId($(this).attr("id")));//移除所有驗(yàn)證的提示 }); //查找所有需要驗(yàn)證格式的文本,若非空,驗(yàn)證格式是否正確 $(getDictTypeClass()).each(function () { if ($(this).val().trim() != "") { checkFormat(getId($(this).attr("id"))); } }); //驗(yàn)證區(qū)間 $("form [id^=txt],[id^=chk]").each(function () { var id = $(this).attr('id'); //文本框 if (id.indexOf("txt") != "-1") { if ($(this).val().trim() != "" && getIsCheckLength(getId(id))) { checkLength(getId(id), $(this).val().trim().length, "text"); } } //多選 else { var options = $("input[name^='" + id + "']:checked").length; if (options > 0 && getIsCheckLength(getId(id))) { checkLength(getId(id), options, ""); } } }); return $(".onerror").length == 0; }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- AngularJs實(shí)現(xiàn)ng1.3+表單驗(yàn)證
- 詳解AngularJS實(shí)現(xiàn)表單驗(yàn)證
- 快速學(xué)習(xí)jQuery插件 jquery.validate.js表單驗(yàn)證插件使用方法
- 常用javascript表單驗(yàn)證匯總
- jquery validate.js表單驗(yàn)證入門(mén)實(shí)例(附源碼)
- javascript html5實(shí)現(xiàn)表單驗(yàn)證
- AngularJS自動(dòng)表單驗(yàn)證
- AngularJS手動(dòng)表單驗(yàn)證
- javascript實(shí)現(xiàn)表單驗(yàn)證
- JS組件Form表單驗(yàn)證神器BootstrapValidator
相關(guān)文章
淺談Webpack自動(dòng)化構(gòu)建實(shí)踐指南
本篇文章主要介紹了Webpack自動(dòng)化構(gòu)建實(shí)踐指南,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-12-12推薦幾個(gè)不錯(cuò)的console調(diào)試技巧實(shí)現(xiàn)
這篇文章主要介紹了推薦幾個(gè)不錯(cuò)的console調(diào)試技巧實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12(function(){})()的用法與優(yōu)點(diǎn)
(function(){})()的用法與優(yōu)點(diǎn)...2007-03-03文字溢出實(shí)現(xiàn)溢出的部分再放入一個(gè)新生成的div中具體代碼
說(shuō)文字溢出,如何實(shí)現(xiàn)溢出的文字放入一個(gè)新生成的div中,原理就是判斷是否能在div里放下,如果不能,則在應(yīng)該斷開(kāi)的地方,差入到新的div中2013-05-05Bootstrap 模態(tài)框(Modal)帶參數(shù)傳值實(shí)例
模態(tài)框(Modal)是覆蓋在父窗體上的子窗體。下面通過(guò)本文給大家介紹Bootstrap 模態(tài)框(Modal)帶參數(shù)傳值實(shí)例代碼,需要的朋友參考下吧2017-08-08javascript省市級(jí)聯(lián)功能實(shí)現(xiàn)方法實(shí)例詳解
這篇文章主要介紹了javascript省市級(jí)聯(lián)功能實(shí)現(xiàn)方法,以不同實(shí)例形式分析了JavaScript實(shí)現(xiàn)省市級(jí)聯(lián)菜單的具體技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-10-10JavaScript支持的最大遞歸調(diào)用次數(shù)分析
這篇文章主要介紹了JavaScript支持的最大遞歸調(diào)用次數(shù)分析,也稱JavaScript支持的最大堆棧數(shù)量,需要的朋友可以參考下2014-06-06javascript實(shí)現(xiàn)計(jì)時(shí)器的簡(jiǎn)單方法
這篇文章主要為大家詳細(xì)介紹了javascript實(shí)現(xiàn)計(jì)時(shí)器的簡(jiǎn)單方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-02-02