asp.net必需字段验证器,至少有一个文本框包含文本

Sha*_*awn 8 c# asp.net

我在asp.net webform上有三个文本框,我是如何/可以使用必需的字段验证器来确保其中至少有一个包含文本?

Ale*_*lex 16

我会像这样使用CustomFieldValidator:

<asp:CustomValidator runat="server"
         ID="MyCustomValidator"
         ValidationGroup="YOUR_VALIDATION_GROUP_NAME"
         OnServerValidate="MyCustomValidator_ServerValidate"
         ErrorMessage="At least one textbox needs to be filled in." />
Run Code Online (Sandbox Code Playgroud)

然后在你的代码隐藏中你有:

protected void MyCustomValidator_ServerValidate(object source, ServerValidateEventArgs args)
{
     if (/* one of three textboxes has text*/)
         args.IsValid = true;
     else
         args.IsValid = false;
}
Run Code Online (Sandbox Code Playgroud)

您还可以向此验证添加客户端组件,并通过使用AJAX工具包的ValidatorCalloutExtender控件扩展它来使其性感.


lin*_*lnk 14

我不认为RequiredFieldValidator符合您的要求.我会CustomValidator指定你的任何一个领域,并在它发射时手动检查它们.

<script>
    function doCustomValidate(source, args) {

        args.IsValid = false;

        if (document.getElementById('<% =TextBox1.ClientID %>').value.length > 0) {
            args.IsValid = true;
        }
        if (document.getElementById('<% =TextBox2.ClientID %>').value.length > 0) {
            args.IsValid = true;
        }
        if (document.getElementById('<% =TextBox3.ClientID %>').value.length > 0) {
            args.IsValid = true;
        }
    }
</script>

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" runat="server" 
         ErrorMessage="have to fill at least 1 field" 
         ControlToValidate="TextBox1" 
         ClientValidationFunction="doCustomValidate"
         ValidateEmptyText="true" ></asp:CustomValidator><br />
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br />
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox><br />
Run Code Online (Sandbox Code Playgroud)

不要忘记设置ValidateEmptyText="true"为默认是跳过空字段.确保您也创建了类似的服务器端验证方法.