ASP.NET中使用自定义验证控件
 
 
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 />

  <%-- Create the CustomValidator control --%>
  <asp:CustomValidator runat="server" />

  <%-- 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" />

  <p><asp:button />
  </form>

 

  可以看到,在验证控件中,   OnServerValidate="PrimeNumberCheck"中,要定义具体的onservervalidate事件,之后,在具体的事件处理过程中,一定要返回args.isvalid的值,以价讲明是否验证成功;当然,最后要用page.isvalid属性来进行全面验证。
 

 

相关文章:

  • 2021-08-26
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-23
  • 2021-04-08
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-10
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案