Filtering TextBoxes with the FilteredTextBoxExtender

Posted Tuesday, November 21, 2006 11:07 AM by C-Dog's .NET Tip of the Day

It's probably about time I started talking about AJAX (previously Atlas), so here we go.  You have probably ran into a time where you need to let a user type free form into a textbox, but you still want to make sure the input is valid.  Of course you can use a validator, but with the FilteredTextBoxExtender you can prevent them from even typing in bad characters.  Extenders make it easy to add new functionality to existing controls such as textboxes, panels, labels, etc. 

The FilteredTextBoxExtender is part of the Ajax Control Toolkit which you can get at ajax.asp.net.  The easiest way to get started with it is (after you have installed ASP.NET AJAX) is to download the toolkit, open the solution, and compile it.  Then include that binary in your web project.

To use the extender start by adding a textbox to the page. The extender has built in functionality to allow only numbers, lower case characters, upper case characters, and custom characters. You can use any combination of the previous. If you use custom, use the ValidChars property to specify the allowed characters. For example, if you wanted to allow floating point numbers, you would set the FilterType to numbers, custom and the ValidChars to . (period). Take a look at the sample below.

<asp:textbox id="MyTextBox" 
runat="server">
<ajaxtoolkit:FilteredTextBoxExtender"
id="MyTextBoxFilter" runat="server"
TargetControlId="MyTextBox"
FilterType="Custom, Numbers"

This like other extenders is quite easy to use and adds useful functionality to many of your existing controls.

Read the complete post at http://www.dotnettipoftheday.com/blog.aspx?id=329