"
ASP.NET (snapshot 2017) Microsoft documentation and samples

Allowing Only Certain Characters in a Text Box (C#)

by Christian Wenz

Download Code or Download PDF

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.

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:

[!code-aspxMain]

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

Then, we need a text box:

[!code-aspxMain]

   1:  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:

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"):

[!code-aspxMain]

   1:  <ajaxToolkit:FilteredTextBoxExtender ID="ftbe" runat="server"
   2:   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

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

Next



Comments ( )
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/web-forms/overview/ajax-control-toolkit/filteredtextbox/allowing-only-certain-characters-in-a-text-box-cs.htm
< THANKS ME>