Lamloumi Afif
Lamloumi Afif

Reputation: 9081

Validation of a checkbox list within Asp.net web forms application

I have a list of checkbox that i need to validate

<asp:CheckBoxList runat="server" ID="listcontrat" >
                                   <asp:ListItem   Value="cdd" >CDD</asp:ListItem>
                                   <asp:ListItem   Value="cdi" >CDI</asp:ListItem>
                                   <asp:ListItem   Value="interim" >Intérim</asp:ListItem>
                                   <asp:ListItem  Value="stage" >Stage/Apprentissage</asp:ListItem>
                                    </asp:CheckBoxList>
                                     <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Champ obligatoire" Text="Champ obligatoire" ForeColor="Red" ControlToValidate="listcontrat"></asp:RequiredFieldValidator>

When i tried this code above i got this error:

Control 'listcontrat' referenced by the ControlToValidate property of 'RequiredFieldValidator2' can not be validated.

So:

Upvotes: 0

Views: 684

Answers (1)

Shanaka Rathnayaka
Shanaka Rathnayaka

Reputation: 2682

try using Customvalidator instead of Requiredfieldvalidator.

<asp:CustomValidator runat="server" ID="cvrequiredcheckboxlist" ClientValidationFunction="ValidateModuleList"
    ErrorMessage="Please Select Atleast one Module" ValidationGroup="test"></asp:CustomValidator>

function ValidateModuleList(source, args) {
            var chkListModules = document.getElementById('<%= listcontrat.ClientID %>');
            var chkListinputs = chkListModules.getElementsByTagName("input");
            for (var i = 0; i < chkListinputs.length; i++) {
                if (chkListinputs[i].checked) {
                    args.IsValid = true;
                    return;
                }
            }
            args.IsValid = false;
        }

This work perfectly.

Cheers. Happy Coding....!!

Upvotes: 2

Related Questions