Sunday, June 13, 2010

Simple Asp.Net Custom Validator Control

Asp.Net Validators are very cool and useful in certain scenarios. There are certain scenarios where Asp.Net required field validator fails such as while validating CheckBox,CheckBoxList etc. The reason for this is because these controls are multiple input controls there is no way for the framework to know which case is valid.

Asp.Net  provides two ways to create CustomValidators.

1) Deriving from System.Web.UI.WebControls.BaseValidator
2) Deriving from System.Web.UI.WebControls.CustomValidator

Here, I have created my custom control by deriving it from CustomValidator class. If you examine the CustomValidator class you will find there is an event "ServerValidate". Developer has to provide a handler and add custom validation logic in that handler.


Framework allows developers to add client side validation by providing the client side validation in the "ClientValidationFunction" property.Framework will call this method to perform the validations.



One of the important thing to remember is "always make your UserControl derive from a custom Base class which extends the Asp.net UserControl class". This way you can add your logic for eg EventHandlers in the custombase class.

SourceCode can be found here.

-Yash