首页 > 编程 > .NET > 正文

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

2024-07-10 12:56:43
字体:
来源:转载
供稿:网友
中国最大的web开发资源网站及技术社区,
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属性来进行全面验证
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表