DIV CSS 佈局教程網

一套可複用的JS表單驗證腳本:class驅動、格式與區間一次搞定
編輯:關於JavaScript     

表單驗證寫久了會發現,真正麻煩的不是寫正則,而是「怎麼讓同一套規則套用到幾十個欄位上還不破功」。本文分享一支以 class 為契約的驗證腳本 Validate-1.0.1.js:只要幫控制項掛上 required、mobile、length_2_5 這類 class,它就會自動接管提示與攔截。

先看成品的樣子:

一、HTML:把規則寫在 class 上

引入 jQuery 與驗證腳本即可,不需要額外初始化設定:

<script src="/Scripts/jquery-1.10.2.js"></script>
<script src="/Scripts/Validate-1.0.1.js"></script>

 <!DOCTYPE html>
 <html xmlns="https://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>長度區間:</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>正整數</th>
 <td class="graytxt1">
 <asp:TextBox ID="TextBox1" runat="server" class="integer" />
 </td>
 </tr>
 <tr>
 <th>小數</th>
 <td class="graytxt1">
 <asp:TextBox ID="TextBox3" runat="server" class="decimal" />
 </td>
 </tr>
 <tr>
 <th>手機</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">無</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項但不超過4項
 </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項
 </td>
 </tr>
 <tr>
 <th>下拉</th>
 <td class="graytxt1">
 <asp:DropDownList ID="drpCode" runat="server" class="drp required">
 <asp:ListItem Value="">請選擇</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>

二、class 命名約定

整支腳本的彈性來自這張對照表,理解了它就能自由擴充:

required 非空;onerror 標記錯誤狀態;length_?_? 區間驗證;rbtn 單選;chk 多選;drp 下拉;mobile 手機;tel 電話;email 郵箱;integer 整數;decimal 數字。

格式驗證集中在 dictType 物件中,key 就是 class 名,value 是「提示文字 + 正則」的組合,要加新格式只需往這裡補一筆。

 /// <reference path="jquery-1.10.2-vsdoc.js" />
 var selectClass = ".rbtn,.chk,.drp";
 function getDictTypeClass() {
 var keys = ".";
 $.each(dictType, function (key, val) {
 keys += key + ",.";
 });
 return keys.substring(0, keys.length - 2);
 }
 var dictType = {
 "mobile": ["手機", /^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": ["整數", /^[1-9]+[0-9]*]*$/],
 "decimal": ["數字", /^[0-9]+.?[0-9]*$/],
 }
 $(function () {
 $(".required").each(function () {
 $(this).parent().append("<em>*</em>");//在必填項後添加 * 標記必填
 });
 try {
 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") {
 message = ($(id).is(selectClass) ? "請選擇" : "請輸入") + $(id).parent().prev().text().trim().replace(':', '').replace(':', '');
 }
 Validate(id, message);
 }
 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;
 var isLength = getIsCheckLength(id);
 if (isLength || isRequired) {
 if (isRequired) {
 if (options > 0) {
 if (isLength == true) { checkLength(id, options, ""); }
 else { RemoveError(id); }
 } else { AddError(id, message); }
 }
 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); }
 }
 }
 }
 else {
 if ($(id).val().trim() !== "") {
 if (getIsCheckLength(id)) { checkLength(id, $(id).val().trim().length, "text"); }
 else { checkFormat(id); }
 } else {
 if (isRequired) { AddError(id, message); } else { RemoveError(id); }
 }
 }
 }
 function getIsRequired(id) { return $(id).hasClass("required"); }
 function getIsCheckLength(id) {
 if (typeof ($(id).attr('class')) != "undefined") {
 return $(id).attr('class').indexOf('length') != "-1";
 } else { return "false"; }
 }
 function checkLength(id, itemLength, text) {
 if (getIsCheckLength(id)) {
 var length = getClassName(id, "length");
 var min = length.split('_')[1], max = length.split('_')[2];
 if (min == 0) {
 var tips = text == "text" ? "最大長度不超過" + max + "位字符" : "需選擇" + max + "項";
 if (itemLength > max) { AddError(id, tips); } else { RemoveError(id); }
 }
 else if (max == 0) {
 if (itemLength < min) { AddError(id, text == "text" ? "請輸入" + (min - 1) + "位以上字符" : "至少選擇" + min + "項"); }
 else { RemoveError(id); }
 }
 else if (min > 0 && max > 0) {
 var tips = text == "text" ? "請輸入" + min + "~" + max + "位的字符" : "需選擇" + +min + "~" + max + "項";
 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>";
 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() === "*") {
 $(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);
 }
 }
 function RemoveError(id) {
 $(id).removeClass("onerror");
 $(id.replace("#", "#sp")).html("");
 }
 function replaceId(id) { return id.replace("#", ""); }
 function getId(id) { return "#" + id; }
 function getClassName(id, className) {
 var clazzs = $(id).attr('class');
 var classIndex = clazzs.substring(clazzs.indexOf(className));
 if (classIndex != "-1") {
 var last = classIndex.indexOf(" ");
 return (last == -1 ? classIndex : classIndex.substring(0, last));
 }
 return "";
 }
 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] + "格式錯誤"); }
 break;
 }
 }
 } else { RemoveError(id); }
 }
 function SubmitValidate() {
 $(".required:input").trigger('blur');
 $(selectClass).trigger('click');
 return $(".onerror").length == 0;
 }
 function SaveValidate() {
 $(".onerror").each(function () { RemoveError(getId($(this).attr("id"))); });
 $(getDictTypeClass()).each(function () {
 if ($(this).val().trim() != "") { checkFormat(getId($(this).attr("id"))); }
 });
 $("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;
 }

三、使用時的幾個約定

第一,需要驗證的控制項要掛 onblur="Check(this)" 或 onclick="Check(this)",若頁面沒有其他自訂邏輯,也可以直接引入 default 版腳本省掉這一步。

第二,length_?_? 的區間驗證在保存時會依控制項 ID 前綴比對(id^=xx),ID 命名必須配合,否則 SaveValidate() 會跳過該項。

第三,若欄位本身已有格式驗證(手機、電話等),腳本就不再檢查長度,避免兩套規則互相打架。

第四,自訂 CSS 的 class 名稱不要與腳本使用的名稱重名,不然樣式與邏輯會互相污染。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved