如何验证列表框是否为空(客户端)

时间:2008-09-24 15:07:40

标签: asp.net validation listbox customvalidator

我正在使用ASP.NET 3.5。 我有一个用户必须添加项目的列表框(我已经为此编写了代码)。我的要求是必须至少将一个项目添加到列表框中,否则他们无法提交表单。我在页面上有几个其他验证器,它们都写入ValidationSummary控件。我希望这个列表框验证也可以写入Validation Summary控件。任何帮助是极大的赞赏。谢谢。

7 个答案:

答案 0 :(得分:5)

放入自定义验证器,向其中添加所需的错误消息,双击自定义验证器以获取事件处理程序的代码,然后您将实现服务器端,如下所示:

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args) 
{
        args.IsValid = ListBox1.Items.Count > 0; 
}

此外,您还可以实现客户端JavaScript。

我只是把它扔到一个页面上并快速测试,所以你可能需要调整一下:( button1只在列表框中添加一个项目)

<script language="JavaScript">
<!--
  function ListBoxValid(sender, args)
  {
      args.IsValid = sender.options.length > 0;
  }
// -->
</script>    
<asp:ListBox ID="ListBox1" runat="server"></asp:ListBox>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" ValidationGroup="NOVALID" />
<asp:Button ID="Button2" runat="server" Text="ButtonsUBMIT"  />

<asp:CustomValidator ID="CustomValidator1" runat="server" 
ErrorMessage="CustomValidator" 
onservervalidate="CustomValidator1_ServerValidate" ClientValidationFunction="ListBoxValid"></asp:CustomValidator>

如果向页面添加验证摘要,只要ValidationGroup中的ListBox或其他可收集控件中没有项目,只要ValidationGroup,就会在该摘要中显示错误文本是一样的。

答案 1 :(得分:5)

这对我不起作用:

function ListBoxValid(sender, args) 
{
        args.IsValid = sender.options.length > 0; 
}

但是这样做了:

function ListBoxValid(sender, args)
{
        var ctlDropDown = document.getElementById(sender.controltovalidate);
        args.IsValid = ctlDropDown.options.length > 0; 
}

答案 2 :(得分:3)

必须确保将这些属性添加到CustomValidator:

Display="Dynamic" ValidateEmptyText="True"

答案 3 :(得分:1)

<asp:CustomValidator 
     runat="server" 
     ControlToValidate="listbox1"
     ErrorMessage="Add some items yo!" 
     ClientValidationFunction="checkListBox"
/>

<script type="Text/JavaScript">
  function checkListBox(sender, args)
  {
      args.IsValid = sender.options.length > 0;
  }
</script>    

答案 4 :(得分:1)

实际上,这是实现这项工作的正确方法(就JavaScript而言)。

ListBox.options.length将始终是您选择的总数,而不是您选择的数字。我找到的唯一方法是使用for循环遍历列表。

function ListBoxValid(sender, args)
{

    var listBox = document.getElementById(sender.controltovalidate);

    var listBoxCnt = 0;

    for (var x =0; x<listBox.options.length; x++)
    {
        if (listBox.options[x].selected) listBoxCnt++;
    }

    args.IsValid = (listBoxCnt>0)

}

答案 5 :(得分:0)

这项工作对我来说

<script language="JavaScript">
  function CheckListBox(sender, args)
  {
      args.IsValid = document.getElementById("<%=ListBox1.ClientID%>").options.length > 0;
  }
</script>    
<asp:ListBox ID="ListBox1" runat="server"></asp:ListBox>
<asp:CustomValidator ID="CustomValidator1" runat="server" 
ErrorMessage="*Required" ClientValidationFunction="CheckListBox"></asp:CustomValidator>

答案 6 :(得分:-1)

您需要通过发送ClientID向页面注册您的控件。然后,您可以使用Microsoft AJAX来获取控件并检查值。

相关问题