Tuesday, August 28, 2012

Validate a CheckBox with a CustomValidator in ASP.NET 4.0 and C#

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. To do this:
Right click the project in your solution explorer.
Select add new item
Select a web form.
Name it ‘Default.aspx’.
Click add.
Open Default.aspx up to design mode.
Drag and drop a checkbox onto the web form.
Drag and drop a customvalidator next to the checkbox.
Change the ErrorMessage property to ‘You must check the box’.
Change the ForeColor property to ‘Red’.
Check the Text property to ‘*’.
Add a line break after the customvalidator.
Drag and drop a button under the checkbox.
Add a line break after the button.
Drag and drop a validationsummary under the button.

Validating the CheckboxNext, we want to add in some simple code on the ServerValidate event of the customvalidator that we added. To do this:
Double click the customvalidator to generate the ServerValidate event method.
Add in the following code to the CustomValidator_ServerValidate event method:

No comments:

Post a Comment