By default there is no validation control in ASP.NET to work with the checkbox control. However, in certain cases you may want to use validation on a checkbox such as one that would require them to accept the terms and services of a web site or registration process.

Adding the Default.aspx Page

To demonstrate this we will need to create a simple web page with a checkbox and a button on it. To do this:

  1. Right click the project in your solution explorer.
  2. Select add new item…
  3. Select a web form.
  4. Name it ‘Default.aspx’.
  5. Click add.
  6. Open Default.aspx up to design mode.
  7. Drag and drop a checkbox onto the web form.
  8. Drag and drop a customvalidator next to the checkbox.
    1. Change the ErrorMessage property to ‘You must check the box’.
    2. Change the ForeColor property to ‘Red’.
    3. Check the Text property to ‘*’.
  9. Add a line break after the customvalidator.
  10. Drag and drop a button under the checkbox.
  11. Add a line break after the button.
  12. Drag and drop a validationsummary under the button.

Validating the Checkbox

Next, we want to add in some simple code on the ServerValidate event of the customvalidator that we added. To do this:

  1. Double click the customvalidator to generate the ServerValidate event method.
  2. Add in the following code to the CustomValidator_ServerValidate event method:

Let’s go over what this code is doing. Whenever validation is initiated, our ServerValidate event method is executed and checks to see if our checkbox is checked. If it is, then we change IsValid to true, if it is not we change IsValid to false.

Testing

To test this out, simply load up the web site and click the button when the checkbox is not checked. You should receive the error message we added earlier. If you then click the button when the checkbox is checked, you should see no errors.
Download Source Files