【问题标题】:asp.net required field validator for at least one textbox contains text至少一个文本框的 asp.net 必填字段验证器包含文本
【发布时间】:2010-10-12 15:00:18
【问题描述】:

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

【问题讨论】:

标签: c# asp.net


【解决方案1】:

我会使用这样的 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." />

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

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

您还可以在此验证中添加一个客户端组件,并通过使用 AJAX 工具包的 ValidatorCalloutExtender 控件对其进行扩展来使其更有吸引力。

【讨论】:

  • 我不喜欢这会导致回发,所以我最终设置了 ClientIDMode="static" 并在 JS 函数中对值进行硬编码。我对做任何错误消息或任何事情并不感兴趣。我只是想让按钮什么都不做。感谢您的代码。它完全有效,只是使用 CustomValidator 是错误的选择。这是我的错,不是你的。
  • 我发现这不会触发指定 ValidationGroup 的验证。一旦我把它拿出来,它就像一个魅力。
【解决方案2】:

我认为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 />

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-20
    • 1970-01-01
    • 2017-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多