[自訂驗證控制項]多擇一必要輸入驗證

  • 7250
  • 0

設計針對Textbox, DropDownList, checkboxlist, radiobuttonlist等input控制項,
驗證至少輸入一項的自訂驗證控制項。

網頁設計上常常很多需求,並不是單純驗證某個textbox或某個dropdownlist為必要輸入。

而是在許多input控制項裡,只要有一個有輸入即可。(例如「住家電話」與「行動電話」兩個textbox,至少輸入其中一項即可)當全都沒輸入時,要顯示驗證錯誤訊息。通常解法都是各自寫各自的java script作驗證,可是自行撰寫java script又不容易與微軟提供的Validator一起驗證,所以就花了一小段時間寫了個很陽春的Custom Validator。使用上還是有諸多不便,不過至少使用上撰寫的方式都是一致的。

 

class:MultiRequireValidator.vb

01 Imports System
02 Imports System.Collections.Generic
03 Imports System.ComponentModel
04 Imports System.Text
05 Imports System.Web
06 Imports System.Web.UI
07 Imports System.Web.UI.WebControls
08 Imports System.Drawing
09 Imports System.Web.Util

10
11 Namespace JoeyTest
12 <ToolboxData("<{0}:MultiRequireValidator runat=server ></{0}:MultiRequireValidator>")> _
13     Public Class MultiRequireValidator
14         Inherits System.Web.UI.WebControls.BaseValidator
15
16         Private _strObjectList As String = String.Empty
17         ''' <summary>
18         ''' 用","把要驗證的objID串起來
19         ''' </summary>
20         ''' <value></value>
21         ''' <returns></returns>
22         ''' <remarks></remarks>
23         <Browsable(True)> Public Overridable Property ObjectListToValidate() As String
24             Get
25                 Return _strObjectList
26             End Get
27             Set(ByVal Value As String)
28                 _strObjectList = Value
29             End Set
30         End Property
31
32         Protected Overrides Sub AddAttributesToRender(ByVal writer As System.Web.UI.HtmlTextWriter)
33             MyBase.AddAttributesToRender(writer)
34
35             If RenderUplevel Then
36                 writer.AddAttribute("evaluationfunction", "MultipleRequiredValidate")
37             End If
38         End Sub

39
40        ''' <summary>
41         ''' 引發 PreRender 事件
42         ''' </summary>
43         ''' <param name="e">包含事件資料的 EventArgs 物件。</param>
44         Protected Overrides Sub OnPreRender(ByVal e As System.EventArgs)
45             MyBase.OnPreRender(e)
46             Me.Attributes("ObjectListToValidate") = _strObjectList        
47         End Sub

48
49     End Class
50 End Namespace

 

aspx,只需include該驗證所需java script,範例為2個textbox與DropDownList,至少輸入一項

01 <script language="JavaScript" type="text/javascript" src="MultiRequire.js"></script>
02 <body>
03     <form id="form1" runat="server">
04     <div>
05         <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
06         <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
07         <asp:DropDownList ID="DropDownList1" runat="server">
08             <asp:ListItem Value=""></asp:ListItem>
09             <asp:ListItem Value="1"></asp:ListItem>
10             <asp:ListItem Value="2"></asp:ListItem>            
11         </asp:DropDownList>
12        
13         <JoeyTest:MultiRequireValidator ID="MultiRequireValidator1" runat="server" ErrorMessage="至少輸入一項" ControlToValidate="TextBox1" Display="none"></JoeyTest:MultiRequireValidator>
14         <asp:Button ID="Button1" runat="server" Text="Button" />
15         <asp:ValidationSummary ID="ValidationSummary1" runat="server" ShowMessageBox="true" ShowSummary="false"/>
16     </div>
17     </form>
18 </body>

vb的Page_Load事件,assign MultiRequireValidator.ObjectListToValidate即可

1 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
2         Me.MultiRequireValidator1.ObjectListToValidate = Me.DropDownList1.ClientID & "," & Me.TextBox1.ClientID & "," & Me.TextBox2.ClientID
3     End Sub

最後就是這個Validator所對應的js 驗證的function

01 function MultipleRequiredValidate(source, arguments)
02 {
03         var str_ObjectListToValidate="";
04   
05    if (document.getElementById&&!document.all)
06   {
07            str_ObjectListToValidate=source.getAttribute("ObjectListToValidate");      
08   }

09   else
10   {
11       str_ObjectListToValidate=source.ObjectListToValidate;      
12   }

13   
14   
15     var ary_ObjectListToValidate=str_ObjectListToValidate.split(",");
16     
17     if (ary_ObjectListToValidate==null){return ;}
18     else
19     {
20      if (ary_ObjectListToValidate.length<=1)
21      {return true;}
22      for(var i=0;i<ary_ObjectListToValidate.length;i++){
23       var ObjectIndex = $getID(ary_ObjectListToValidate[i]);
24       var strValue="";
25       if (ObjectIndex.value==null)
26       {
27            if (__ValidateCheckBoxListItems(ObjectIndex))
28            {return true;}
29                     
30       }

31       else
32       {
33           strValue=ObjectIndex.value;        
34           strValue=strValue.replace(/ /g ,"");                
35           strValue=strValue.replace(/ /g ,"");
36           if (strValue != "")
37           {return true;}
38       }

39             
40   }

41      return false;
42     }

43 }

44
45 //checkboxlist
46 function __ValidateCheckBoxListItems(val)
47 {
48     //var objCtl = document.all[val.controltovalidate];
49     //var colItems = objCtl.all;
50     var colItems = val.all;
51     for(var i=0;i<colItems.length;i++){
52   if (colItems.item(i).tagName == "INPUT") {
53       if ( colItems.item(i).checked ) {
54     return true;
55       }

56   }

57     }

58
59 }

60
61

目前使用上還是得在vb裡面加上clientID,畢竟先應急囉,

有空再把該屬性加工一下,應該可以在使用上更方便。

PS:CheckBoxList跟RadioButtonList是否有輸入,也可以使用唷。


blog 與課程更新內容,請前往新站位置:http://tdd.best/