Language

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:

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

Author Information

Christian Wenz

Christian Wenz – Christian Wenz is an author, trainer, and consultant. His main focus of working and writing is on web technologies and security. Christian has written or co-written over 100 books for various publishers. He works with both open source and closed source web technologies. This leads to the unusual situation that he has both been awarded a Microsoft MVP for ASP/ASP.NET and is listed in Zend's Who is Who of PHP. He is also listed in Mozilla's credits (about:credits) and is considered an expert in browser-agnostic JavaScript.