日期:2013-12-07  浏览次数:20980 次

不久前,注册CSDN时,发现每次在离开一个textbox控件时,都有可能出现错误提示。
以前用ASP时,都是通过点 “确定”按钮,然后在提交页面时,对其进行验证,相比之下,ASP.NET更显友好和方便,于时自己也动手试了试:

首先,定义一个textbox控件,

<asp:TextBox ID="studentid" runat="server" MaxLength="14" Columns="14" TabIndex="1" AutoPostBack="true" OnTextChanged="studentid_textchanged" ToolTip="学生证上的号码!"/>

大家知道,.NET中有个验证控件:
<asp:RequiredFieldValidator ControlToValidate="studentid" ErrorMessage="学号没有输" runat="server"/>

通过它,可以对上面定义的studentid这个textbox验证,检验是否为空,但有时,这个功能往往是不够的,所以我们就要用到textbox的 ontextchanged 和 atuopostback 两个属性,


当atuopostback设为 "true " 时,每当textbox失去焦点和文本框中内容改变时,都会触发 ontextchanged 中设置的事件,所以,我们可以把验证代码写到 ontextchanged 的事件中, 那样在我们就可以实现 CSDN 注册时类似的功能.

整个代码如下:
'检测学号输入是否正确
sub studentid_textchanged(Sender as object, E as eventargs)
dim studentid_text as string
studentid_text=studentid.text
if studentid.text="" then
lable1.text="学号不能为空"
elseif len(studentid_text)<7 then
lable1.text="学号不能小于7位数"
elseif len(studentid_text)>10 then
lable1.text="学号不能大于10位数"
else
lable1.text=""
end if
end sub
'提交表单
</script>

<asp:TextBox ID="studentid" runat="server" MaxLength="14" Columns="14" TabIndex="1" AutoPostBack="true" OnTextChanged="studentid_textchanged" ToolTip="学生证上的号码!"/>
<asp:Label id="lable1" Font-Size="14px" ForeColor="#FF3300" runat="server"/>
<asp:RequiredFieldValidator ControlToValidate="studentid" ErrorMessage="学号没有输" runat="server"/>