How do I validate that a list box is not empty (client side)

chris picture chris · Sep 24, 2008 · Viewed 20.4k times · Source

I'm working with ASP.NET 3.5. I have a list box that users must add items to (I've written the code for this). My requirement is that at least one item must be added to the listbox or they cannot submit the form. I have several other validators on the page and they all write to a ValidationSummary control. I would like this listbox validation to write to the Validation Summary control as well. Any help is greatly appreciated. Thank you.

Answer

stephenbayer picture stephenbayer · Sep 24, 2008

Drop in a custom validator, Add your desired error message to it, double click on the custom validator to get to the code behind for the event handler, and then you would implement server side like this:

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

Also you can implement client side javascript as well.

I just threw this up on a page and tested it quickly, so you might need to tweak it a bit: (The button1 only adds an item to the List Box)

<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>

If you add a validation summary to the page, you error text should show up in that summary if there is no items in the ListBox, or other collection-able control, what ever you want to use, as long as the ValidationGroup is the same.