说明:我有两个文本框,用户可以选择填写两个文本框,但必须填写用户至少填写其中一个文本框。
预期结果:显示错误消息 意外结果:错误消息未显示
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;
}
请你能帮忙解释为什么不是这个工作人员?
答案 0 :(得分: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;
}
答案 1 :(得分:1)
&&
表示and
,如果两个长度均为0则无效,请尝试
bool b = false;
if (TB1.Text.Length != 0)
b = true;
if (TB2.Text.Length != 0)
b = true;
e.IsValid = b;
答案 2 :(得分:0)
试试这个:
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"/>