Apr 27, 2011

Asp.Net ListBox CustomValidator

Hi folksMy objective there was to have a custom validating function to test if a listbox was empty.

<asp:ListBox ID=”lBox” SelectionMode=”Multiple” runat=”server” Width=”150px”></asp:ListBox>
The validator
<asp:CustomValidator ID=”cv1″ ErrorMessage=”The list box is empty” OnServerValidate=”cv1_ServerValidate” Display=”Dynamic” SetFocusOnError=”True” ControlToValidate=”lBox” ValidateEmptyText=”true” runat=”server” ClientValidationFunction=”ListBoxValid”></asp:CustomValidator>

I just spent around 20 minutes trying to understand WHY my custom validation client script function
was not working for my listbox. And here is the final solution.
My major mistake was to not include the ValidateEmptyText=”true” directive in my custom validating control. This was causing the CustomValidatorEvaluateIsValid Microsoft function to return true if the
 listbox was empty.
Here’s the code
First the javascript function
function ListBoxValid(sender, args) {
args.IsValid = document.getElementById(sender.controltovalidate).options.length>0;
}
The listbox


A dummy button
<asp:Button ID=”btnTest” runat=”server” Text=”Button” CausesValidation=”true” />
And the server side function, just in case
protected void cv1_ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = lBox.Items.Count > 0;
}
I hope that this will help many of you ;)

Tested under IE7 && FF3

SERVER SIDE VALIDATION:

<asp:CustomValidator ID="cv1" ErrorMessage="Select Group Name" OnServerValidate="cv1_ServerValidate" Display="Dynamic" SetFocusOnError="true" ControlToValidate="lstSelGName_Sel" ValidateEmptyText="true" runat="server" ClientValidationFunction="ListBoxValid"></asp:CustomValidator>



cv1_ServerValidate(object source, ServerValidateEventArgs args)

protected void
{
if (lstSelGName_Sel.Items.Count > 0)
args.IsValid = true;
else
args.IsValid = true;
}

No comments:

Post a Comment