Eri*_*ard 28 c# asp.net validation customvalidator
我有一个必需的字段验证器和自定义验证器来验证texbox.必需的字段验证器完全触发.我无法正确启动自定义验证器?
<asp:TextBox ID="txtPRI" runat="server" Width="295" /><br />
<asp:RequiredFieldValidator display="Dynamic" CssClass="leftAlign" SetFocusOnError="true" runat="server" controltovalidate="txtPRI" errormessage="Please enter your PRI" />
<asp:CustomValidator runat="server" id="cusCustom" controltovalidate="txtPRI" onservervalidate="cusCustom_ServerValidate" Enabled="true" ValidateEmptyText="true" display="Dynamic" CssClass="leftAlign" SetFocusOnError="true" errormessage="The text must be exactly 8 characters long!" />
Run Code Online (Sandbox Code Playgroud)
代码背后
protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e)
{
Response.Write("firing - test");
Response.End();
if (e.Value.Length == 8)
e.IsValid = true;
else
e.IsValid = false;
}
Run Code Online (Sandbox Code Playgroud)
Kel*_*sey 49
检查是否已将CustomValidator
属性ValidateEmptyText
设置为,true
以便验证空文本.那你就不再需要RequiredFieldValidator
了.
编辑:我把你的代码复制并粘贴到一个空的项目中,它按预期工作.必须有一些你没有发布或发布错误的东西,我们不知道.是否还有其他因素会影响触发验证的按钮或验证控件本身?
编辑:这是确切的代码(它在内容页面中):
aspx页面:
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:TextBox ID="txtPRI" runat="server" Width="295" /><br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" display="Dynamic" CssClass="leftAlign" SetFocusOnError="true" runat="server" controltovalidate="txtPRI" errormessage="Please enter your PRI" />
<asp:CustomValidator runat="server" id="cusCustom" controltovalidate="txtPRI" onservervalidate="cusCustom_ServerValidate" Enabled="true" ValidateEmptyText="true" display="Dynamic" CssClass="leftAlign" SetFocusOnError="true" errormessage="The text must be exactly 8 characters long!" />
</asp:Content>
Run Code Online (Sandbox Code Playgroud)
.cs页面(空Page_Load
):
protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e)
{
// put a break point here and it stops on it
if (e.Value.Length == 8)
e.IsValid = true;
else
e.IsValid = false;
}
Run Code Online (Sandbox Code Playgroud)
Pat*_*ick 18
好的......真的很老问题还没有接受答案,我刚刚遇到了同样的问题.
所以我打算把这个问题扔给那些可能有这个问题需要答案的人......
如果您正在进行常规验证以及自定义服务器验证,那么只有在所有其他验证都恢复干净的情况下才会触发自定义服务器验证,至少这是对我的工作方式.
小智 5
除了上面的建议之外,我发现使用较新版本的 .Net 框架,您必须在服务器上显式触发 validate() 方法以获取自定义验证器例程
// validate page before allowing import to go through
Page.Validate();
if (!Page.IsValid)
return;
Run Code Online (Sandbox Code Playgroud)
问题是您正在调用Response.End()
这实际上会停止页面的所有执行。因此,if/else 块根本没有运行。在调试时注释掉该行或跳过它,验证器将按预期触发。
我建议您使用调试器,而不是以这种方式编写响应,或者注意Response.End()
如果您选择使用它的后果。