CodeKicks.com
Focus on Microsoft Technologies - Tutorials, Articles, Code Samples.

Monday, September 25, 2006

Creating Validator Controls for the CheckBox and CheckBoxList

Introduction
ASP.NET provides a variety of validation Web controls that can be used to validate a user's form field inputs. (See Form Validation with ASP.NET - It Doesn't Get Any Easier! for general information on the validation Web controls and Dissecting Validation Controls in ASP.NET 2.0 for the validation control changes from ASP.NET version 1.x to ASP.NET version 2.0.) 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. Many Web pages with Terms of Service include a CheckBox titled "I agree to the above terms" that must be checked before continuing. Likewise, a Web Form may contain a set of options in the form of a CheckBoxList. Perhaps the user is required to check at least one of these options before continuing. To provide such validation, we have three choices:

  1. 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.
  2. 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. (See Using the CustomValidator Control for more information on this topic.)
  3. 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.

The CheckBoxValidator in the Designer in Visual Studio
The CheckBoxValidator in the Designer in Visual Studio
 

Find More From ScottGu

Post a Comment