Monthly Archives: July 2011

Validating Checked Controls in ASP.net

This is one that pretty much every ASP.net web forms developer will come across every now and then.

What to do when you have a bunch of  check boxes or radio buttons in some kind  of common container: Table, list, even a check box list, etc, and you need to make sure at least one is checked.

One way to handle this is to use a custom validator:

<asp:CustomValidator 
     ID="custEventVal" 
     runat="server" 
     ErrorMessage="Please Select An Event"
     ClientValidationFunction="ValidateEvents" 
     EnableClientScript="true" 
     Display="Dynamic" 
     onservervalidate="custEventVal_ServerValidate">
</asp:CustomValidator>

With client side validation:

//Requires jQuery
//#SelEvent is the id of our containing element
//in this case we are checking for radio buttons
function ValidateEvents(sender, args) {
    args.IsValid = ($("#SelEvent input:radio:checked").length > 0);
}

and server side:

/// <summary>Ensure radio button has been selected</summary>
/// <param name="source"></param>
/// <param name="args"></param>
protected void custEventVal_ServerValidate(object source, ServerValidateEventArgs args)
{
    int eventID;
    //in this instance our radio buttons are set up with the name
    //rdoEvents
    args.IsValid = (!String.IsNullOrEmpty(Request.Form["rdoEvent"]));
}

This will work on when the form is submitted but the validation error will still remain regardless of if one on the controls is checked. To resolve this use jQuery to wire up ValidatorHookupControlID, which is provided by the ASP.net validation frame work.

//#SelEvent is the id of our containing element
//in this case we are checking for radio buttons
$(document).ready(function() {
   $("#SelEvent input:radio").each(function() {
       ValidatorHookupControlID($(this).attr('id'), document.all["<%= custEventVal.ClientID %>"]);
   });
 });