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
property to the
ID of a CheckBox or CheckBoxList, the page will throw an
"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:
- 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
- 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.)
- 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.
In this article we'll implement the third option, creating two custom server controls, CheckBoxValidator and CheckBoxListValidator.
The download at the end of this article includes both the entire source code and a compiled assembly that you can drop into
your ASP.NET 2.0 web applications. Read on to learn more!
The server controls provided in this article were designed using Visual Studio 2005 and the .NET Framework 2.0's base class libraries;
consequently, they will only work in ASP.NET 2.0 applications. If you are still using ASP.NET 1.x, check out
Creating a Validation Control for CheckBoxLists.
Alternatively, you may adapt the code presented here to work in ASP.NET 1.x.
Read More >