Introduction
Every time I used ASP.NET and Ajax validation, I didn't like it. I literally wrote more than 5 lines of XML to validate a single textbox control, it took too much time, made debugging code very difficult and I don't like too much code in one place. Then I got this idea. I made a user control for textbox and wrote validation for it, now if you have 5 or 6 textboxes in one form. You will have to write 5 or 6 lines for all of them.
Using the Code
First, I created a user control for the textbox the code is as under:
TXBXX.ASCX File
<%@ Control Language="C#" AutoEventWireup="true"
CodeFile="TXBXX.ascx.cs" Inherits="UserControls_TXBXX" %>
<%@ Register Assembly="AjaxControlToolkit"
Namespace="AjaxControlToolkit" TagPrefix="ajax" %>
<asp:textbox id="TX" runat="server" textmode="SingleLine" />
<asp:requiredfieldvalidator id="RF" runat="server"
errormessage="-" controltovalidate="TX"
display="None" setfocusonerror="True" />
<ajax:validatorcalloutextender id="VC" runat="server"
targetcontrolid="RF" enabled="True">
TXBXX.ASCX.CS File
public partial class UserControls_TXBXX : System.Web.UI.UserControl
{
public string Text
{
get
{
return TX.Text.Trim();
}
set
{
TX.Text = value.Trim();
}
}
public string CSS
{
set
{
TX.Attributes.Add("class", value);
}
}
public string Validation
{
set
{
TX.ValidationGroup = value;
RF.ValidationGroup = value;
}
}
public string ErrMsg
{
set
{
RF.ErrorMessage = value;
}
}
public TextBoxMode TextMode
{
set
{
TX.TextMode = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
And this is how we use it:
Import the control:
<%@ Register Src="../../UserControls/TXBXX.ascx"
TagName="TXBXX" TagPrefix="TXBX" %>
Use the control:
<TXBX:txbxx runat="server" textmode="MultiLine"
validation="newnote" errmsg="Please Provide Name" id="TX_Name" />
Here is an example of this same code you would use otherwise:
<asp:textbox runat="server" id="TX_Name">
<asp:requiredfieldvalidator setfocusonerror="true"
errormessage="Please Provide Name" display="None"
validationgroup="newnote" controltovalidate="TxBx_Name"
runat="server" id="RFV_Name">
<ajax:validatorcalloutextender enabled="True"
targetcontrolid="REV_Name" runat="server" id="VCE_REV_Name">
Points of Interest
It helped me in coding quickly, it saved my time, my code is clean and short and I can easily set values of a textbox at one go. I hope it helps you too. :) Please send me your feedback on
nasir_ml@hotmail.com.
History
- 9th January, 2014: Initial post