验证消息错误无法正常工作

时间:2017-07-26 08:13:03

标签: c# asp.net webforms

我遇到了网络表单验证邮件错误的问题。当两个语句都为真时我都需要得到一个错误(两个字段都是空的)。当我为 || 更改语句&& 时,我能够收到错误,但这不是我想要的。谢谢。这是我的C#代码

protected void CustomValidatorForm_ServerValidate(object source, ServerValidateEventArgs args)
    {
        if (string.IsNullOrEmpty(drpState.Text) && string.IsNullOrEmpty(txtRegion.Text))
            args.IsValid = false;
        else
        {
            args.IsValid = true;
        }
    }

我正在尝试为我的表单运行此代码:

<asp:DropDownList ID="drpState"  runat="server" CausesValidation="True">
<asp:ListItem></asp:ListItem>
<asp:ListItem Value="IL">Illinois</asp:ListItem>
<asp:ListItem Value="IN">Indiana</asp:ListItem>
<asp:ListItem Value="IA">Iowa</asp:ListItem>
 </asp:DropDownList>
    <asp:TextBox ID="txtRegion" runat="server"></asp:TextBox>
    <asp:Button ID="btnSubmit" Text="Submit" runat="server"  />

        </div>
            <asp:CustomValidator ID="CustomValidatorList" runat="server"
                 ControlToValidate ="drpState" OnServerValidate="CustomValidatorForm_ServerValidate"
                 ErrorMessage="At least one of the field need to be filled out" Display="Dynamic"
                 ForeColor="Red"
                >

            </asp:CustomValidator>
            <asp:CustomValidator ID="CustomValidatorForm" runat="server"
                ControlToValidate ="txtRegion" OnServerValidate="CustomValidatorForm_ServerValidate"
                ErrorMessage="At least one of the field need to be filled out" Display="Dynamic"
                ForeColor="Red"

                >

            </asp:CustomValidator>

2 个答案:

答案 0 :(得分:0)

尝试使用这样的,

<asp:TextBox ID="txtFrom" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ErrorMessage="*" ControlToValidate="txtFrom" runat="server" Display="Dynamic" ForeColor="Red" />

简单方法,

创建<asp:TextBox ID="txtFrom" runat="server"></asp:TextBox>

输入<asp:RequiredFieldValidator并按Tab Button两次, 您还可以提供任何ErrorMessage以及定义ErrorMessage的颜色

答案 1 :(得分:0)

事实证明我只需添加此属性ValidateEmptyText="True"并将其设置为true。这就是验证器应该是这样的:

<asp:CustomValidator ID="CustomValidatorList" runat="server"
     ControlToValidate ="drpState" OnServerValidate="CustomValidatorForm_ServerValidate"
     ErrorMessage="At least one of the field need to be filled out" Display="Dynamic"
     ForeColor="Red" ValidateEmptyText="True">
</asp:CustomValidator>