Scott on Writing

Musings on technical writing...

My Wife's First Contribution to 4Guys

Like yours truly, my wife also creates ASP.NET applications for a living.  I shudder to think what our future children will be like, perhaps they'll be bilingual from an early age, speaking both English and C#.  A common question on many newsgroups and online forums is how to use the validation controls in ASP.NET 1.x to limit the user's input to a specified number of characters.  The typical answers are, “Use the TextBox's MaxLength property,” or, “Use a CustomValidator.”  I was never a big fan of either of these approaches - the former still requires server-side code since a nefarious user could easily cirumvent this setting in their browser; the latter approach is better, but not very portable to other pages or Web sites, as the server-side and (optional) client-side code must be repeated on each page/site that utilizes the CustomValidator.

So, I've always wanted to write a custom validation control that provided this functionality.  It's been on my TODO list for a while, but has very low priority.  Anywho, my ol' lady had a slow day at work a week ago or so, and decided to whip up this control that's been on my plate for a while.  She's not a fan of writing like yours truly, so I whipped up an article describing her code and illustrating how to use the control - you can learn more at Creating a TextBoxLengthValidator Validation Control.  There's a live demo available here.  You can download the complete source code, along with a compiled assembly, here.

Enjoy!

posted on Tuesday, November 23, 2004 12:29 PM

Feedback

# re: My Wife's First Contribution to 4Guys 11/23/2004 5:26 PM bestcomy

a really usefule control.
by the way,are your wife is a chinese? cause her name is Jisun Lee

# re: My Wife's First Contribution to 4Guys 11/23/2004 9:21 PM Scott Mitchell

She was born in South Korea, moved to the states when she was a toddler.

# re: My Wife's First Contribution to 4Guys 11/24/2004 8:40 AM Eric Madariaga

Nice control.

One can also handle this kind of problem with a regularexpressionvalidator by setting the validation expression.

e.g. If you want to limit the length of a textbox to 20 characters you could set:

validationexpression=".{0,20}"



# re: My Wife's First Contribution to 4Guys 11/28/2004 6:08 AM Guy Baron

Nice Control + Article,
However I would add another property that would let the consumer of the control declare how he would like an input that contains all white spaces be evaluated, and factor that in the validation routine.

# re: My Wife's First Contribution to 4Guys 11/28/2004 1:14 PM Rajeev Gopal

Wonderful!

But, to be honest, I would go Eric Madariga's way.

Hey, who can stop you creating controls? You are really a control freak :-)

# re: My Wife's First Contribution to 4Guys 11/29/2004 8:44 AM Michael

I guess you can't call it 4Guys anymore, eh?

# re: My Wife's First Contribution to 4Guys 12/2/2004 3:32 AM Gavin Lyons

Love regular expression too ..

But I like the example, it was helpful to understand how controls work.

I updated your control to sport mininum length too.

/// <summary>
/// TextBoxLengthValidator - orginal authored by Jisun Lee, extended to support mininum values by Gavin Lyons
/// </summary>
[ToolboxData("<{0}:TextBoxLengthValidator runat=server ErrorMessage=\"TextBoxLengthValidator\"></{0}:TextBoxLengthValidator>")]
public class TextBoxLengthValidator : BaseCompareValidator
{
/// <summary>
/// Specifies the maximum length of the TextBox the control is validating. If this value
/// is less than 0, then inputs of any length are considered valid.
/// </summary>
[Bindable(true),
Description("Specifies the maximum length of the TextBox the control is validating. If this value is less than 0, then inputs of any length are considered valid."),
Category("Behavior"),
DefaultValue(-1)]
public int MaximumLength
{
get
{
object MaxLengthVS = this.ViewState["MaximumLength"];
if (MaxLengthVS != null)
{
return (int) MaxLengthVS;
}
return -1;
}
set
{
this.ViewState["MaximumLength"] = value;
}
}
/// <summary>
/// Specifies the minimum length of the TextBox the control is validating. If this value
/// is less than 0, then inputs of any length are considered valid.
/// </summary>
[Bindable(true),
Description("Specifies the minimum length of the TextBox the control is validating. If this value is less than 0, then inputs of any length are considered valid."),
Category("Behavior"),
DefaultValue(-1)]
public int MinimumLength
{
get
{
object MinLengthVS = this.ViewState["MinimumLength"];
if (MinLengthVS != null)
{
return (int) MinLengthVS;
}
return -1;
}
set
{
this.ViewState["MinimumLength"] = value;
}
}
#region Overriden Methods
/// <summary>
/// Adds client-side functionality for uplevel browsers by specifying the JavaScript function
/// to call when validating, as well as a needed parameter (the MaximumLength property value).
/// </summary>
protected override void AddAttributesToRender(HtmlTextWriter writer)
{
base.AddAttributesToRender(writer);
if (base.RenderUplevel)
{
writer.AddAttribute("evaluationfunction", "TextBoxLengthValidatorIsValid");
writer.AddAttribute("maximumlength", this.MaximumLength.ToString());
writer.AddAttribute("minimumlength", this.MinimumLength.ToString());
}
}

/// <summary>
/// Checks to ensure that the ControlToValidate property is set to a TextBox
/// </summary>
protected override bool ControlPropertiesValid()
{
if (base.FindControl(base.GetControlRenderID(base.ControlToValidate)).GetType() != new System.Web.UI.WebControls.TextBox().GetType())
throw new HttpException("Control to Validate of must be a text box.");
return base.ControlPropertiesValid();
}

/// <summary>
/// Performs the server-side validation. If MaximumLength is less than 0, always returns True;
/// otherwise, returns True only if the ControlToValidate's length is less than or equal to the
/// specified MaximumLength.
/// </summary>
protected override bool EvaluateIsValid()
{
bool MaxLenForValidate = false;
bool MinLenForValidate = false;

string ControlToValidateName = base.GetControlValidationValue(base.ControlToValidate);

if (this.MaximumLength > 0) MaxLenForValidate = (ControlToValidateName.Length <= System.Convert.ToInt32(this.MaximumLength));
else MaxLenForValidate=true;

if (this.MinimumLength > 0) MinLenForValidate = (ControlToValidateName.Length >= System.Convert.ToInt32(this.MinimumLength));
else MinLenForValidate = true;

if (MinLenForValidate && MaxLenForValidate) return true;
else return false;
}

/// <summary>
/// Injects the JavaScript function that performs client-side validation for uplevel browsers.
/// </summary>
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);

if (base.RenderUplevel)
Page.RegisterClientScriptBlock("TxtBxLngthValIsValid",
@"<script language='javascript'>
function TextBoxLengthValidatorIsValid(val)
{var maxb=false;var minb=false;var value=ValidatorGetValue(val.controltovalidate);if (val.maximumlength>0) {if (value.length<=val.maximumlength) {maxb=true;} else {maxb=false;}} else {maxb=true};if (val.minimumlength>0) {if (value.length>=val.minimumlength) {minb=true;} else {minb=false;}} else {minb=true};if (maxb && minb) {return true;} else {return false;}}
</script>");
}
#endregion
}

# re: My Wife's First Contribution to 4Guys 9/26/2005 2:16 AM gavin

For user controls it will give an object reference error. Here's little workaround which is incomplete, if anyone wants to fill in the blanks.. :-)


protected override bool ControlPropertiesValid()
{
string CtrlToValName=base.ControlToValidate;
if (base.NamingContainer.ClientID!=null)
{
// User controls, Datagrid etc...

}
else
{
if (base.FindControl(base.GetControlRenderID(base.ControlToValidate)).GetType() != new System.Web.UI.WebControls.TextBox().GetType())
throw new HttpException("Control to Validate of must be a text box.");
}
return base.ControlPropertiesValid();
}

Title:  
Name:  
Url:
Protected by Clearscreen.SharpHIPEnter the code you see:
Comments   

My Links

Ads Via DevMavens

Archives

Post Categories

 

I am a Microsoft MVP for ASP.NET.
I am an ASPInsider.
<March 2010>
SMTWTFS
28123456
78910111213
14151617181920
21222324252627
28293031123
45678910

Comment Stats

DayTotal% of Total
Sunday 2056.8%
Monday 42514.1%
Tuesday 51917.2%
Wednesday 55618.4%
Thursday 58019.2%
Friday 54718.1%
Saturday 1886.2%
Total 3020100.0%

Hour1Total% of Total
12:00 AM 782.6%
1:00 AM 812.7%
2:00 AM 682.3%
3:00 AM 822.7%
4:00 AM 692.3%
5:00 AM 1264.2%
6:00 AM 1193.9%
7:00 AM 1816.0%
8:00 AM 1926.4%
9:00 AM 1585.2%
10:00 AM 1886.2%
11:00 AM 1936.4%
12:00 PM 2016.7%
1:00 PM 1846.1%
2:00 PM 1695.6%
3:00 PM 1354.5%
4:00 PM 1153.8%
5:00 PM 1073.5%
6:00 PM 1013.3%
7:00 PM 1073.5%
8:00 PM 923.0%
9:00 PM 882.9%
10:00 PM 913.0%
11:00 PM 953.1%
Total 3020100.0%

Comments by Blog Entry Date/Time

Day Entry MadeAvg.Total
Sunday 5.00160
Monday 4.80384
Tuesday 4.04477
Wednesday 7.39680
Thursday 6.26676
Friday 5.07466
Saturday 4.78177
Total 5.403020

Hour1 Entry MadeAvg.Total
12:00 AM 5.2937
1:00 AM 1.002
5:00 AM 0.000
7:00 AM 3.8550
8:00 AM 3.72134
9:00 AM 6.06297
10:00 AM 5.63276
11:00 AM 4.22194
12:00 PM 6.16351
1:00 PM 3.09133
2:00 PM 4.89230
3:00 PM 7.67322
4:00 PM 4.00108
5:00 PM 6.07170
6:00 PM 4.64116
7:00 PM 8.95188
8:00 PM 8.63164
9:00 PM 5.00115
10:00 PM 6.31101
11:00 PM 4.5732
Total 5.403020

Learn More About Comment Stats
1 - All times GMT -8...


Blog Stats

Favorite Web Sites

My Books

My MSDN Articles