June 22, 2009

Enforcing MaxLength On TextBox Controls

If you use ASP.NET, you've probably encountered situations where you need to restrict the overall length of input and you've tried using the MaxLength property on the TextBox controls.

For the most part, that works. Most browsers properly restrict the length on the client side. However, some browsers do not properly restrict the entry length, some browsers have loopholes that allow overlong entry (copy/paste, etc.), and you can't forget malicious users.

So you can properly restrict the sizes using ASP.NET's validators, do the following.

Drag over a CustomValidator and point it to the TextBox you want to enforce length limits on.

Point the CustomValidator's ServerValidate function to this function...



protected void TextLength_ServerValidate(object source, ServerValidateEventArgs args)
{
CustomValidator v = (CustomValidator)source;
if (v != null)
{
TextBox t = (TextBox)this.FindControl(v.ControlToValidate);
if (t != null && t.MaxLength > 0)
{
args.IsValid = args.Value.Length <= t.MaxLength;
return;
}
}
args.IsValid = true; // If custom validator wasn't set up correctly, assume valid
}

No comments: