Click here to Skip to main content
15,881,089 members
Articles / Programming Languages / C#
Article

Using Custom Validator to Validate Checkbox

Rate me:
Please Sign up or sign in to vote.
4.55/5 (5 votes)
30 Oct 2007CPOL2 min read 71.3K   431   13   2
Performing validation of checkbox using custom validator

Introduction

There are some server controls for which Custom validator can't be applied. CheckBox control is one such control. Custom validator eases the validation logic written by the developer. When I had a requirement in my project to validate the CheckBox control, I Googled and found a lot of examples using client side validation. As I needed to do a server side validation, I decided to write a custom control to meet my requirements. I am posting the control here so that other developers like me can use it.

Background

Before developing this control, I was going through MSDN, which suggested not to set the ControlToValidate property of the CustomValidator. When I followed the same, there were no issues but if we use more than one such control in the same ASPX page, then identifying the source is not possible. Adding a lot of similar custom validator code for each checkbox control doesn't seem to a fair solution to me. Keeping this in mind I have created this composite control which by default checks whether the checkbox is selected and then shows an error message appropriately in case of failure. As businesses always change from project to project, I have also included a validation event in the control, using which one can write his/her own business logics in the code behind Class. The validation can also be turned on and off by setting a property Validate.

Using the Code

I have created a Custom control by creating a class CheckBoxControl by extending the composite control and implementing the INamingContainer. Any web app can simply include this DLL as a reference and then import the controls in the ASPX page using the following:

ASP.NET
<%@ Register Assembly="SS.Web.UI.Controls" Namespace="SS.Web.UI.Controls"
    TagPrefix="SS"  %>

At the minimum, we have the checkbox and a custom validator to validate inside the Custom Control.

C#
protected CheckBox chkBox = new CheckBox();
protected CustomValidator cvCustomVal = new CustomValidator();

I have exposed certain properties like Checked, Caption, ValidationGroup, Validate, ErrorMessage to change their normal behaviour.

Child controls are created and ensured by the overriding CreateChildControls method:

C#
#region Child Controls
    protected override void CreateChildControls()
    {
        base.CreateChildControls();
        // assign ids and other properties
        chkBox.ID = this.ID + "_chk1";
        cvCustomVal.ID = this.ID + "_Validator";
        cvCustomVal.EnableClientScript = false;
        cvCustomVal.ErrorMessage = ErrorMessage;
        cvCustomVal.Text = "!";
        // add the controls.
        Controls.Add(new LiteralControl("<tr><td>"));
        Controls.Add(chkBox);
        Controls.Add(cvCustomVal);
        Controls.Add(new LiteralControl("</td></tr>"));
    }
    #endregion 

OnInit method takes care of wiring up the validation event to the custom validator:

C#
protected override void OnInit(EventArgs e)
{
    if (!string.IsNullOrEmpty(ValidationGroup))
    {
        chkBox.ValidationGroup = ValidationGroup;
        cvCustomVal.ValidationGroup = ValidationGroup;
    }
    cvCustomVal.ServerValidate +=
        new System.Web.UI.WebControls.ServerValidateEventHandler
        (this.validator_ServerValidate);
    base.OnInit(e);
}

The following code shows the validation section of the control. If the application has initialized the event ValidateEvent, then just raise the event, or else perform the predefined validation. This feature will be of great help for writing any specific business validation. The attached source has examples for writing the specific business validation.

C#
#region validation Event

    protected void validator_ServerValidate
        (object source, ServerValidateEventArgs args)
    {
        if (ValidateEvent != null)
        {
            OnValidateEvent(args);
        }
        else
        {
            if (Validate && (!chkBox.Checked))
            {
                args.IsValid = false;
                cvCustomVal.ErrorMessage = ErrorMessage;
            }
        }
    }
    #endregion

Conclusion

Similar logic can be used for other controls for which the custom validator can't be applied directly.

History

  • Oct 30 2007 - Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
India India
Web App Developer, Chennai, India

Comments and Discussions

 
GeneralThanks a lot Pin
feretyz16-May-09 7:34
feretyz16-May-09 7:34 
AnswerA more simple method... Pin
kriceslo3-Sep-08 6:07
kriceslo3-Sep-08 6:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.