skip to content
Linkedin Twitter feed logo
15 February 2008

Check Validator – An ASP.NET Validator Control

Check Validator used with checkbox

While some developers assume that the classical ASP.NET validators support check boxes and radio buttons, this isn’t the case! There is a logical explanation for this; there is nothing much to check, the checkbox can only be checked or unchecked so what do you want to validate?

In some cases you might want to display an error if a check box or a radio button is unchecked, e.g. terms and conditions check box, if so, then this is the right validator for you. Read on if you are interested in the bits and pieces of how the control works or skip to the “Using The Validator” section if you are just interested in using it.

Background

Usually control classes that supports validation are decorated with the ValidationProperty attribute, for example, the TextBox control looks like this:

// more attributes...
[ValidationProperty("Text")]
// more attributes...
public class TextBox : WebControl, IPostBackDataHandler, 
  IEditableTextControl, ITextControl 
{
    ...
}

The ValidationProperty will point the validator at the property to validate against.

The CheckBox, RadioButton, HtmlInputCheckBox and HtmlInputRadioButton lack this attribute, accordingly, any standard validation control will throw an exception Control 'ControlID' referenced by the ControlToValidate property of 'ValidatorID' cannot be validated when set against one of these controls.

Architecture

This validator inherits, as in most validators, from BaseValidator and overrides method ControlPropertiesValid that issues this exception.

protected override bool ControlPropertiesValid() 
{
  if (ControlToValidate.Trim().Length == 0) {
    throw new HttpException(
      string.Format(@"The ControlToValidate property of
      {0} cannot be blank.", ID));
  }

  Control control = FindControl(ControlToValidate);

  if (control == null) {
    throw new HttpException(
      string.Format (
        "Could not locate control with ID {0}", 
        ID)
    );
  }

  if (!(control is CheckBox) &&
      !(control is RadioButton) &&
      !(control is HtmlInputCheckBox) &&
      !(control is HtmlInputRadioButton)) 
  {
          throw new HttpException(
          @"ControlToValidate can only be
          System.Web.UI.WebControls.CheckBox,
          System.Web.UI.WebControls.RadioButton,
          System.Web.UI.HtmlControls.HtmlInputCheckBox,
          System.Web.UI.HtmlControls.HtmlInputRadioButton");
  }

  return true;
}

The rest of the server side code is classical. The validator has a property called WarnIf which will reverse checking (when set to false, the validator will warn if the box is checked).

This is the client-side validation code:

function CheckValidatorEvaluateIsValid(val) 
{
  var control = document.getElementById(val.controltovalidate);
  var warnif = val.warnif == 1 ? true : false;
  return control.checked ^ warnif;
}

Using the Validator

To use this validator from your Visual Studio IDE, you need to add the provided .dll to the toolbox. For more information on this, check the
>MSDN documentation.

Drop the control on the form and assign it to the CheckBox/RadioButton that you want to check:

<at:CheckValidator
    Text="I have read the terms and conditions"
    ControlToValidate="_termsAndConditions"
    Text="Accept terms before proceeding" />

Licence

This software is disributed under Ms-PL. Which simply means, you can freely use it and distribute it but you must retain all copyright, patent, trademark, and attribution notices that are present in the software.


Finally, if you like the article and find the control useful, then please Kick It (using the button below) and it would be kind of you to leave a comment. All suggestions and bug reports are welcome. I have also created the MultipleFieldsValidator validator control to tackle the problem of validating multiple controls.

Download CheckValidator.zip (16.97 kb)

11Comments
leave your own
  • SHIBASHEESH DEY June 4th, 2008

    I am also a software developer and i want some of the tips to increase the performance of my project.
    As i also want to be a best and confident Software Developer like you. If possible send me some more
    tips to do best code related to performance.

  • Prabu W June 11th, 2008

    Im interested to know how (if possible) asp.net validators can be used for groups of radiobuttons. The validation is to check atleast one of the group of radiobuttons have been checked. The groupname attribute has been used to group the asp radiobutton controls. I find it hard to believe MS left this case out of the validation controls, but i can seem to figure out do it.

  • A. VIKRAM REDDY June 18th, 2008

    please tell me about asp.net validation controls..
    and also a book with more no. of programs for practice n a book for theory.
    ok, letz back to our focus….give me all asp.net validation controls in detail

  • ramya August 27th, 2008

    how to validate the radio button .., whethr any one got checked r not

  • Adam Tibi August 27th, 2008

    Hi Ramya,

    Using a normal required field validator will do the job, but remember you should be using Radio Button List rather than single radio buttons.

    Regards
    Adam

  • Natalie September 16th, 2008

    Adam,

    Thank you for providing the DLL for download and an example on how to reference.

    It saved me a lot time to try to implement on my own and now I can reference on all my web pages.

    Great tip and time saver!

    Thanks again,
    Natalie

  • Marc October 23rd, 2008

    Great! Thanks!!

  • Wasim November 4th, 2008

    Thanks for the control, however it doesn’t seem to work when inside a CreateUserWizard control.

  • Matt November 4th, 2008

    I need to validate that at least 2 boxes were checked in a CheckBoxList. Any ideas?

  • Jeremy December 17th, 2008

    Hi Adam, I need to validate that at least one of 20 check boxes is checked, what is the best way?

    Thanks

  • bubba January 2nd, 2009

    Sweet! Thank you. It does work with the create user wizard with some tweaking. I don’t know what I did but it is working.
    Thanks!!!

Leave a Reply

Gravatar