ASP.NET中使用自定義驗證控制元件(原作)
阿新 • • 發佈:2019-02-10
asp.net 1.1中,有不少驗證控制元件,大大方便了我們,但有的時候,當需要做特殊的驗證時,還會覺得不夠用的,於是我們可以用自定義驗證控制元件CustomValidator,要使用這個控制元件,必須在服務端寫相應的事件,格式如下:
Sub FunctionName(sender as Object, args as ServerValidateEventArgs) ... End Sub 其中注意兩個引數
value:指示當前的CustomValidator驗證的是哪一個控制元件
IsValid:為真時,表示頁面控制元件已經通過驗證。
舉一個驗證頁面中文字框的輸入是否為素數的例子:
<script language="vb" runat="server"> Sub btnSubmit_Click(sender as Object, e as EventArgs) If Page.IsValid then Response.Write("<font color=""red""><i>" & txtPrimeNumber.Text & _ " is, indeed, a good prime number.</i></font>") Else Response.Write("<font color=""red""><i>" & txtPrimeNumber.Text & _ " is <b>not</b> a prime number.</i></font>") End If End Sub Sub PrimeNumberCheck(sender as Object, args as ServerValidateEventArgs) Dim iPrime as Integer = Cint(args.Value), iLoop as Integer, _ iSqrt as Integer = CInt(Math.Sqrt(iPrime)) For iLoop = 2 to iSqrt If iPrime mod iLoop = 0 then args.IsValid = False Exit Sub End If Next args.IsValid = True End Sub </script> <form method="post" runat="server"> Enter your favorite prime number: <asp:textbox id="txtPrimeNumber" runat="server" /> <%-- Create the CustomValidator control --%> <asp:CustomValidator runat="server" id="custPrimeCheck" ControlToValidate="txtPrimeNumber" OnServerValidate="PrimeNumberCheck"ErrorMessage="Invalid Prime Number" /> <%-- Create two CompareValidator controls: the first ensures that the number entered by the user is an Integer; the second makes sure it is positive. --%> <asp:CompareValidator runat="server" id="compPrimeNumber" Operator="DataTypeCheck" Type="Integer" Display="Dynamic" ControlToValidate="txtPrimeNumber" ErrorMessage = "You must enter an integer value." /> <asp:CompareValidator runat="server" id="compPrimeNumberPositive" Operator="GreaterThan" Type="Integer" Display="Dynamic" ValueToCompare="0" ControlToValidate="txtPrimeNumber" ErrorMessage = "You must enter a value greater than zero." /> <p><asp:button id="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Submit" /> </form> 可以看到,在驗證控制元件中, OnServerValidate="PrimeNumberCheck"中,要定義具體的onservervalidate事件,之後,在具體的事件處理過程中,一定要返回args.isvalid的值,以價講明是否驗證成功;當然,最後要用page.isvalid屬性
來進行全面驗證