ChrisW
ChrisW

Reputation: 1

How do I validate multiple asp.net checkboxes in C#

I have spent a lot of time trying to get 4 checkboxes to validate in a web application. This web app has already been written, and uses checkboxes when it probably should use a checkboxlist. However, I believe it will be an inordinate amount of work to change all of the existing code, so being able to validate the existing 4 boxes would save me a total re-write.

I have been through stackoverflow looking for the answer for two days, and I found several answers that will help me if I have a single checkbox, but I can't get anything to work if I have multiple, and I just want to validate a single box.

Below is the checkbox info for the ascx form:

                                        </asp:Panel>
                                    <cc1:PopupControlExtender ID="PopupControlExtender1" PopupControlID="PanelTypeOwnership"
                                        runat="server" TargetControlID="helpTypeOwnership" Position="Left">
                                    </cc1:PopupControlExtender>
                                                <strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Type of Ownership:</strong></td> 
                                            <td class="style12">
                                                &nbsp;</td>
                                            <td class="style11">
                                            </td>
                                            <td>
                                                <strong>
                                                            <div class="textBoxImg" id="helpTypeOwnership" runat="server" style="width: 24px;
                                                                float: right;">
                                                            </div>

                                                </strong>
                                            </td>
                                        </tr> 
                                        <tr>
                                            <td style="padding-left: 2px;" class="style2">
                                                    <asp:CheckBox ID="chbAgricultural" runat="server" CssClass="texLabel" Text="&nbsp;&nbsp;Agricultural/Horticultural Society"
                                BorderStyle="None" Width="260px" />
                                            </td>
                                            <asp:CustomValidator runat="server" ID="validateCheckBoxes" EnableClientScript="true"
                                            OnServerValidate="validateCheckBoxes_ServerValidate"
                                            ClientValidationFunction="validateCheckBoxes_ServerValidate">Please select a type of ownership.</asp:CustomValidator>
                                            <td valign="middle" align="left" class="style10">
                            <asp:CheckBox ID="chbEnducational" runat="server" CssClass="texLabel" 
                                Text="&nbsp;&nbsp;Educational" />
                                    </td> 
                                            <td class="style12">
                            <asp:CheckBox ID="chbReligious" runat="server" CssClass="texLabel" 
                                Text="&nbsp;&nbsp;Religious" />
                                            </td>
                                            <td class="style11">
                            <asp:CheckBox ID="chbCharitable" runat="server" CssClass="texLabel" 
                                Text="&nbsp;&nbsp;Charitable" />
                                            </td>
                                        </tr> </table>
                                        <div style="height: 39px;">
                                        </div>

The code relating to the checkbox validation on the ascx.cs form is:

    protected void validateCheckBoxes_ServerValidate(object source, ServerValidateEventArgs args)
{
    if (!chbAgricultural.Checked && !chbEnducational.Checked && !chbReligious.Checked && !chbReligious.Checked)
        args.IsValid = false;
    else
        args.IsValid = true;
}

The code for the submit button is:

    protected void lbnSubmit_Click(object sender, EventArgs e)              

        {
          if (Page.IsValid)
        {


        MembershipUser mUser = Membership.GetUser(Page.User.Identity.Name);
        if (mUser == null) return;


        DateTime dateT = Convert.ToDateTime(TextBoxDateWrite.Text);
        FairShareApplication451a.changeStatusToVoid(new Guid(mUser.ProviderUserKey.ToString()), GetParcelId());
        FairShareApplication451a apl451a = FairShareApplication451a.CreateApplication451a(new Guid(mUser.ProviderUserKey.ToString()),
               lblNumberApplication.Text, TextBoxCounty.TextBoxText, TextBoxTaxyear.TextBoxText, TextBoxContactName.TextBoxText, TextBoxContactPhone.TextBoxText, TextBoxStateIncorporated.TextBoxText,    //
            GetParcelId(), chbAgricultural.Checked, chbEnducational.Checked, chbReligious.Checked, chbCharitable.Checked, TextBoxOrganizationName.TextBoxText, TextBoxPropOwnerName.TextBoxText,//
            TextBoxMailingAddress.TextBoxText,
            TextBoxCity.TextBoxText, DDListControl2.SelectedValue, TextBoxZipCode.TextBoxText, //TextBoxState.TextBoxText
            TextBoxPropertyDescriptions.TextBoxText,
            TextBoxAuthorizedSignature.Text, TextBoxTitle.Text, dateT, "Not Reviewed",
            PropertyAddress.TextBoxText, PropertyCity.TextBoxText, PropertyState.SelectedValue, PropertyZip.TextBoxText); // Convert.ToDateTime(TextBoxDateWrite.Text)

        //save uploaded files
        SaveUploadedFiles(apl451a.Id);
        FileUploader1.ResetControl();

        MailSend m_snd = new MailSend(Server, Request);
        m_snd.SendMessage(apl451a.UserId, FairShare.MailSend.mailType.received);
        Response.Redirect("~/securezone/CurrentApplications.aspx");
        //       ClearAll();
        }
}

I am sure I am missing something. I am still able to submit forms without checking any boxes. Any help would be greatly appreciated.

Note: I am aware educational is spelled incorrectly. I inherited this site --I just haven't gotten around to changing it in all of the relevant places.

Upvotes: 0

Views: 3361

Answers (3)

E-Bat
E-Bat

Reputation: 4892

Why to give up with client side validation? In your CustomValidator you have: OnServerValidate="validateCheckBoxes_ServerValidate" and
ClientValidationFunction="validateCheckBoxes_ServerValidate"

You have ClientValidationFunction pointing to the same server function. Try something like the following: ClientValidationFunction="validateCheckBoxes_CLIENTValidate"

Being the client function something like this:

<script type="text/jscript">
    function validateCheckBoxes_CLIENTValidate(sender, e) {
        e.IsValid = jQuery(".texLabel input:checkbox").is(':checked');
    }
</script>

If you cannot resolve multiple checkbox values by css class name you can take a look to this link

Upvotes: 0

Raja Nadar
Raja Nadar

Reputation: 9499

Another option is to create a property on the ASCX user control

public bool IsOneCheckboxChecked
{
 get
 {
  return (chbAgricultural.Checked || chbEnducational.Checked || chbReligious.Checked || chbCharitable.Checked);
 }
}

You can then remove this method: (and maybe avoid a postback in the process)

protected void validateCheckBoxes_ServerValidate

and when it is time to submit the form, check:

if (userControlInstance.IsOneCheckboxChecked) 
{
 // good to go.
}

Upvotes: 2

Andrew Morton
Andrew Morton

Reputation: 25066

To check if one or more of the checkboxes is checked, you just need

args.IsValid = (chbAgricultural.Checked || chbEnducational.Checked || chbReligious.Checked || chbCharitable.Checked)

(you had chbReligious in there twice).

And I'm fairly sure you need to tie the CustomValidator to a Control to check, unless there is something else in the page which isn't shown.

Upvotes: 1

Related Questions