Recently I created a post to show you how to create a custom control with two-way binding. I will now use this same project and add validation to this custom control text box.
This web control will inherit from the TextBox web control, and will automatically add a required field validation at run-time. This control will do custom validation on the control without using the required field validation. I will regard this as part 2 of custom controls.
I have created this project in the two-way binding post and you can download the full project from here. You can also download this project from the download button at the bottom of this post.
Custom control Class (cs)
For this custom control we will not use a web user control (ascx) but instead use a class that will inherit from the System.Web.UI.WebControls.TextBox control.
Create a new class file and call it RequiredTextBox.cs. Add the following code:
using System; using System.Web.UI; using System.Web.UI.WebControls; namespace TwoDataBidingControl.Controls { public class RequiredTextBox : TextBox { private RequiredFieldValidator _required; public string InvalidMessage; public string ClientScript = "true"; protected override void OnInit(EventArgs e) { _required = new RequiredFieldValidator { ControlToValidate = ID, ErrorMessage = InvalidMessage, EnableClientScript = (ClientScript.ToUpper() != "FALSE") }; Controls.Add(_required); } protected override void Render(HtmlTextWriter w) { base.Render(w); _required.RenderControl(w); } } } |
We defined a class called RequiredTextbox which inherits from the System.Web.UI.WebControls.TextBox class. The default text box don’t have an invalid message tag or a field validator set to it, so we define this in the code. We can then pass the InvalidMessage and clientScript value to the control. Note that we will set the ClientScript to false as validation will be done in server-side.
Custom Control Page (aspx)
Now we create a asp.net page and call this custom control.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TextBoxValidation.aspx.cs" Inherits="TwoDataBidingControl.Controls.TextBoxValidation" %> <%@ Register TagPrefix="uc" Namespace="TwoDataBidingControl.Controls" Assembly="TwoDataBidingControl" %> |
When you run this you will get something like this: