views:

4681

answers:

6

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.

A: 

You will want to register your control with the page by sending in the ClientID. Then, you can use Microsoft AJAX to grab your control and check the values.

Jason N. Gaylord
+3  A: 

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.

stephenbayer
A: 

The custom validator raise at selectedindex change (on the client side), does anyone know how to indicate which event to use for the validation?

A: 
<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>
FlySwat
+1  A: 

This didn't work for me:

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

But this did:

function ListBoxValid(sender, args)
{
        var ctlDropDown = document.getElementById(sender.controltovalidate);
        args.IsValid = ctlDropDown.options.length > 0; 
}
Naeem Sarfraz
A: 
Zack Rose