TextBox的Validator和TextChanged事件

文章详细介绍了在ASP.NET Web应用程序中,当TextBox输入非整数时,如何避免RangeValidator报错及正确触发TextChanged事件的方法。通过实例演示了错误方法和正确方法,包括设置CauseValidato属性、重写TextChanged事件方法以及在提交按钮的Click事件中验证有效性。文章还强调了在提交表单前验证整个页面的有效性的必要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我的页面上有TextBox,我使用RangeValidator来确保TextBox输入的是整数,TextBox有TextChanged事件。

<asp:TextBox ID="txtID" runat="server" AutoPostBack="true" OnTextChanged="txtID_TextChanged" MaxLength="15" ValidationGroup="selfValidation"></asp:TextBox>
<asp:RangeValidator ID="rvID" runat="server" Display="Dynamic" ControlToValidate="txtID"
Type="Integer" MinimumValue="1" MaximumValue="2147483647" Text="Invalid ID" ValidationGroup="selfValidation"
></asp:RangeValidator>


我在TextBox框中输入字符,比如"a"。

我发现RangeValidator 报错“Invalid ID”,同时TextChanged事件也被触发。

怎样避免呢?

1,错误方法。给TextBox添加CauseValidato="True"。

我再在TextBox框中输入字符,比如"a"。TextChanged事件不会被触发,但是,我点提交按钮时,TextChanged事件在ButtonClick事件前被触发。仍然报错。

 

2,正确方法。

protected void txtID_TextChanged(object sender, EventArgs e)
        {
            rvID.Validate();
            if (!rvID.IsValid)
            {
                return;
            }

 

 

另外,在提交按钮的Click事件中最好添加

if (!Page.IsValid)
                return;

这样即使黑客把javascript禁用了,也不能提交成功。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值