Blogger :
Scott on Writing
All posts :
All posts by Scott on Writing
Category :
ASP.NET
Blogged date : 2006 Sep 20
ASP.NET provides a variety of validation Web controls that can be used to validate a user's form field inputs. Unfortunately, the validation Web controls do not work with the CheckBox or CheckBoxList Web controls. If you set a validation control's ControlToValidate property to the ID of a CheckBox or CheckBoxList, the page will throw an HttpException, stating: "Control 'controlID' referenced by the ControlToValidate property of 'validationControlID' cannot be validated."
There may be times, however, when you need to provide validation for a CheckBox or CheckBoxList. In fact, a rather popular article on 4Guys is Creating a Validation Control for CheckBoxLists by Cenk Civici and yours truly, which shows how to create a CheckBoxList validation control to ensure that at least one checkbox from the list is selected. Similarly, I recently got an email from a reader of my Working with Data in ASP.NET 2.0 tutorial series asking about validating a CheckBox being checked. For example, many Web pages with Terms of Service include a CheckBox titled "I agree to the above terms" that must be checked before continuing.
To provide such validation, we have three choices:
- Forgo any sort of validation Web control semantics and perform the validation check using code on postback. The downside of this is that it breaks from the standard validation control metaphor and requires extra effort to include client-side validation.
- Use the CustomValidator control and define our own server-side and client-side validation logic. The benefit of this approach is that it adheres to the validation control metaphor; however, the validation logic is tightly bound to the ASP.NET page, meaning that the server-side and client-side validation must be replicated on all pages that need to validate a CheckBox or CheckBoxList.
- Create a custom, compiled validation server control that provides the functionality needed. The benefit of this approach is that we have a reusable, easily deployable custom server control that adheres to the validation control metaphor. Unfortunately, this option requires the most upfront code/effort.
Yesterday, I decided to write a custom, compiled validation control for the CheckBox and one for the CheckBoxList using the .NET Framework 2.0 (thereby targetting ASP.NET 2.0). Unlike the CheckBoxListRequiredFieldValidator created by Cenk, these two validators also include client-side script validation support. You can download the CheckBoxValidator and CheckBoxListValidator controls from My Code Projects; a discussion on the CheckBoxList control can be found in the latest 4Guys article, Creating Validator Controls for the CheckBox and CheckBoxList.