2010-11-03 110 views
2

我有一个要求多个字段之一是必需的。使用自定义验证程序甚至会触发,返回false,但不会显示错误消息并验证表单。没有自定义验证器的错误消息

我错过了什么?我曾尝试使用和不使用ValidationSummary。

谢谢!

<asp:CustomValidator ID="CustomValidator1" OnServerValidate="validatePhone" EnableClientScript="false" runat="server" ErrorMessage="Home or Cell Phone is Required" ></asp:CustomValidator> 

<asp:ValidationSummary ID="ValidationSummary1" DisplayMode="BulletList" runat="server" ForeColor="Red" Font-Size="X-Small" Font-Bold="true" /> 


protected void validatePhone(object sender, ServerValidateEventArgs e) 
    { 
     e.IsValid = string.IsNullOrEmpty(txtCellPhone.Text) && string.IsNullOrEmpty(txtHomePhone.Text) ? false : true; 
    } 

回答

1

问题完全是我的错。在我的提交按钮上,我做的最后一件事是一个Response.Redirect。消息即将出现,但随后谢幕页正在呈现。现在只需要执行Response.Redirect,如果customvalidator返回true。

+0

如果'Page.IsValid = true',你应该只处理代码。这将检查ValidationGroup中的所有验证器是否有效。否则,您可以绕过JavaScript进行验证。 – rtpHarry 2013-05-24 10:29:05

1

您必须将ControlToValidate设置为某个TextBox。

<asp:CustomValidator ID="CustomValidator1" OnServerValidate="validatePhone" EnabEnableClientScript="false" runat="server" ErrorMessage="Home or Cell Phone is Required" ControlToValidate="txtHomePhone"/> 
+0

设置ControlToValidate不会验证控件是否为空。由于我正在验证多个控件,所以这不起作用。 – Bleeped 2010-11-04 15:47:45

1

结账this article。基本上你需要连接客户端验证。 添加以下之前关闭表单标签更改控制名称需要:

<%-- This configures the validator to automatically--%> 
<%-- update when either of these controls is changed --%> 
<script type="text/javascript"> 
    <!-- 
     ValidatorHookupControlID("<%= MyControl1.ClientID %>", 
     document.getElementById["<%= CustomValidator1.ClientID %>"]); 
     ValidatorHookupControlID("<%= MyControl2.ClientID %>", 
     document.getElementById["<%= CustomValidator1.ClientID %>"]); 
    //--> 
</script> 

或者使用this control

+0

得到它的工作,而不需要客户端 – Bleeped 2010-11-04 15:45:56