ASP.NET中使用自定义验证控件

80酷酷网    80kuku.com

  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 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属性来进行全面验证

分享到
  • 微信分享
  • 新浪微博
  • QQ好友
  • QQ空间
点击: