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

被折叠的 条评论
为什么被折叠?



