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   

Add To Your Reader

My Links

Archives

Post Categories

 

I am a Microsoft MVP for ASP.NET.
I am an ASPInsider.
<May 2008>
SMTWTFS
27282930123
45678910
11121314151617
18192021222324
25262728293031
1234567

Comment Stats

DayTotal% of Total
Sunday 1866.8%
Monday 37913.9%
Tuesday 45316.7%
Wednesday 50418.5%
Thursday 53519.7%
Friday 49418.2%
Saturday 1666.1%
Total 2717100.0%

Hour1Total% of Total
12:00 AM 652.4%
1:00 AM 682.5%
2:00 AM 622.3%
3:00 AM 742.7%
4:00 AM 572.1%
5:00 AM 1033.8%
6:00 AM 1084.0%
7:00 AM 1585.8%
8:00 AM 1716.3%
9:00 AM 1475.4%
10:00 AM 1716.3%
11:00 AM 1816.7%
12:00 PM 1886.9%
1:00 PM 1696.2%
2:00 PM 1605.9%
3:00 PM 1324.9%
4:00 PM 1073.9%
5:00 PM 923.4%
6:00 PM 913.3%
7:00 PM 963.5%
8:00 PM 833.1%
9:00 PM 782.9%
10:00 PM 792.9%
11:00 PM 772.8%
Total 2717100.0%

Comments by Blog Entry Date/Time

Day Entry MadeAvg.Total
Sunday 5.54144
Monday 5.22339
Tuesday 4.28419
Wednesday 7.67637
Thursday 6.90607
Friday 5.48411
Saturday 5.33160
Total 5.842717

Hour1 Entry MadeAvg.Total
12:00 AM 5.0035
1:00 AM 1.002
5:00 AM 0.000
7:00 AM 7.0035
8:00 AM 5.35107
9:00 AM 6.32278
10:00 AM 6.47246
11:00 AM 4.41181
12:00 PM 6.88330
1:00 PM 3.00111
2:00 PM 5.41222
3:00 PM 8.64285
4:00 PM 4.0589
5:00 PM 5.92154
6:00 PM 4.52113
7:00 PM 9.67174
8:00 PM 9.80147
9:00 PM 5.05111
10:00 PM 5.4265
11:00 PM 4.5732
Total 5.842717

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


Blog Stats

Favorite Web Sites

My Books

My MSDN Articles