2

说明:我有两个文本框,用户可以选择填写,但用户必须至少填写其中一个。

预期结果:显示错误消息 意外结果:未显示错误消息

HTML:

<asp:TextBox ID="TB1" runat="server" /> 
<asp:CustomValidator ID="CV1" ControlToValidate="TB1" runat="server" OnServerValidate="blabla" ErrorMessage="one of two required" />
<asp:TextBox ID="TB2" runat="server" />
<asp:CustomValidator ID="CV2" ControlToValidate="TB2" runat="server" OnServerValidate="blabla" ErrorMessage="they cant both be blank" />

C#:

protected void blabla(object sender, ServerValidateEventArgs e)
{
    if (TB1.Text.Length == 0 && TB2.Text.Length == 0)
        e.IsValid = false; 
    else
        e.IsValid = true; 
}

请你能帮忙解释一下为什么这不是工作人员吗?

4

3 回答 3

5

两者只需要一个CustomValidator。它是唯一一个您可以省略这种ControlToValidate情况的验证器。

aspx:

<asp:TextBox ID="TB1" runat="server" /> 
<asp:TextBox ID="TB2" runat="server" />
<asp:CustomValidator ID="CV1"runat="server" 
    OnServerValidate="ServerValidation" 
    ErrorMessage="one of two required" />

代码隐藏:

protected void ServerValidation(object source, ServerValidateEventArgs args)
{
    args.IsValid = TB1.Text.Trim().Length > 0 || TB2.Text.Trim().Length > 0;
}
于 2013-04-17T08:22:32.727 回答
1

&&意味着and如果两个长度都是 0 那么它是无效的,试试

bool b = false;
if (TB1.Text.Length != 0)
b = true;

if (TB2.Text.Length != 0)
b = true;

e.IsValid = b; 
于 2013-04-17T08:22:26.767 回答
1

尝试这个:

protected void blabla(object sender, ServerValidateEventArgs e)
{
    if (string.IsNullOrEmpty(TB1.Text) && string.IsNullOrEmpty(TB2.Text))
        e.IsValid = false;
    else
        e.IsValid = true;
}

使用ValidationGroup属性也很有用:

<asp:TextBox ID="TB1" runat="server" /> 
<asp:CustomValidator ID="CV1" ControlToValidate="TB1" runat="server" OnServerValidate="blabla" ErrorMessage="one of two required" validationgroup="validationGroup" />
<asp:TextBox ID="TB2" runat="server" />
<asp:CustomValidator ID="CV2" ControlToValidate="TB2" runat="server" OnServerValidate="blabla" ErrorMessage="they cant both be blank" validationgroup="validationGroup" />

<asp:button id="ValidateButton" text="Validate" validationgroup="validationGroup" runat="server"/>
于 2013-04-17T08:29:46.940 回答