ASP.NET includes the TextBox control and the Validation controls which can be combined together to perform user input validation. The caveat is that the developer has to use two different controls to perform a simple validation. In this article we are going to create a custom TextBox control which will use different validation controls and reduce the complexity of using multiple controls.
We have created a separate class library project called MyControlsLibrary which will host all the server controls. We will call our control RequiredTextBox control. The RequiredTextBox control will derive from the ASP.NET TextBox control and add the validators as composite controls. Let's add a RequiredFieldValidator to the RequiredTextBox control.
Adding a RequiredFieldValidator to the RequiredTextBox Control:
Our first task is to add a RequiredFieldValidator to our new RequiredTextBox control. Here is the code:
The first thing to notice is the name of the property "RequiredTextBoxErrorMessage". We have provided a descriptive property name instead of the simple "ErrorMessage". The reason is that we will be adding other validators which will also have the ErrorMessage property. So, we are differentiating the validator error message properties by using descriptive names.
The CreateRequiredFieldValidator method is fired on the PreRender event and is used to create the RequiredFieldValidator control and then add it to the controls collection.
Adding the RegularExpressionValidator Feature to the RequiredTextBox Control:
Just like we added the RequiredTextBoxValidator control to our RequiredTextBox control we can add a RegularExpressionValidator control. The RegularExpressionValidator will ensure that the TextBox input is valid against the validation expression set by the user.
Here is the complete code used by the RequiredTextBox control:
Using the RequiredTextBox Control:
Let's use our new RequiredTextBox control on a ASP.NET page. The first thing that you must do is add a reference to the MyControlsLibrary class library project. Now, you need to register the assembly to the page so you can use the new RequiredTextBox control.
And here is the usage of the control:
In this article we build a custom RequiredTextBox server control which performs the RequiredFieldValidation and RegularExpressionValidation by setting few properties on the control. In the future articles we will demonstrate how to inject custom client side code with our web server control.
It is a much better idea to create the child controls inside the CreateChildControls method than inside the PreRender event. Simply, overwrite the CreateChildControls method and create child controls.