我的页面上有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禁用了,也不能提交成功。