Page view counter

Allowing Only Certain Characters in a Text Box

This is the Visual Basic tutorial    (Switch to the Visual C# tutorial)

ASP.NET validation controls can ensure that only certain characters are allowed in user input. However this still does not prevent users from typing invalid characters and trying to submit the form.

Download the code for this tutorial   |   Download the tutorial in PDF format   |   View a demo

Allowing Only Certain Characters in a Text Box

Christian Wenz

Overview

ASP.NET validation controls can ensure that only certain characters are allowed in user input. However this still does not prevent users from typing invalid characters and trying to submit the form.

Steps

The ASP.NET AJAX Control Toolkit contains the FilteredTextBox control which extends a text box. Once activated, only a certain set of characters may be entered into the field.

For this to work, we first need—as usual—the ASP.NET AJAX ScriptManager which loads the JavaScript libraries which are also used by the ASP.NET AJAX Control Toolkit:

<asp:ScriptManager ID="asm" runat="server" />

Then, we need a text box:

Numbers only: <asp:TextBox ID="TextBox1" runat="server" />

Finally, the FilteredTextBoxExtender control takes care of restricting the characters the user is allowed to type. First, set the TargetControlID attribute to the ID of the TextBox control. Then, choose one of the available FilterType values:

  • Custom—default; you have to provide a list of valid chars
  • LowercaseLetters—lowercase letters only
  • Numbers—digits only
  • UppercaseLetters—uppercase letters only

If the Custom FilterType is used, the ValidChars property must be set and provide a list of characters that may be typed. By the way: if you try to paste text into the text box, all invalid chars are removed.

Here is the markup for the FilteredTextBoxExtender control that only allows digits (something that would also have been possible with FilterType="Numbers"):

<ajaxToolkit:FilteredTextBoxExtender ID="ftbe" runat="server"      TargetControlID="TextBox1" ValidChars="1234567890" />

Run the page and try to enter a letter—if JavaScript is enabled, it will not work; digits however appear on the page. However note that the protection FilteredTextBox provides is not bullet-proof: If JavaScript is enabled, any data may be entered in the text box, so you have to use additional validation means, i.e. ASP.NET’s validation controls.

Only digits may be entered (Click to view full-size image)

Next Tutorial

Visual Basic Tutorials

(Switch to Visual C# tutorials)

Microsoft Communities