Abstract:
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.

Getting Started:

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:

public class RequiredTextBox : TextBox
{
public string RequiredTextBoxErrorMessage { get; set; }

private RequiredFieldValidator _requiredFieldValidator;

protected override void CreateChildControls()

{
CreateRequiredFieldValidator();

base.CreateChildControls();
}
private void CreateRequiredFieldValidator()
{
_requiredFieldValidator = new RequiredFieldValidator
{
ControlToValidate = ID,
ErrorMessage = RequiredTextBoxErrorMessage
};

Controls.Add(_requiredFieldValidator);
}

protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
_requiredFieldValidator.RenderControl(writer);

}
}

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.

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.

<%@ Register Assembly=”MyControlsLibrary” Namespace=”MyControlsLibrary” TagPrefix=”mycontrols” %>

And here is the usage of the control:

<form id=”form1″ runat=”server”>
<div>

<mycontrols:RequiredTextBox ID=”txtName” runat=”server” RequiredTextBoxErrorMessage=”This field cannot be left empty!” />

</div>
</form>

if it is helpful, plese dont forget to leave a comment.