Click here to Skip to main content
14,297,239 members

Filtered Textbox

Rate this:
2.18 (6 votes)
Please Sign up or sign in to vote.
2.18 (6 votes)
9 Oct 2005
Demonstrates how to impliment a textbox who's input is regulated via. a regular expression.


Have you ever needed to create a textbox that only allows you to enter numbers? Or letters? Or strings that don't start with a number? C# 2.0 addresses this point to a certain extent with the masked textbox. However, this does not help if you need to use more complex rules to define the validation.

To this end, I created a FilteredTextBox, that uses a regular expression filter to define what can be entered in the textbox. If it cannot be entered, it will not appear (unlike a post-validation, that would create an error message, or cleanup and remove invalid characters after)

Using the Code

To use the compiled componant, enter a regular expression that for any acceptable string in the textbox will create a match in the Filter property.

Adding Sound

I excluded this to enable the code to work with .NET 1.1 However, if you are using 2.0, or can do something similar in 1.1, it may be a good idea to provide audio feedback when an invalid character is typed. I did this by adding a boolean property of ShouldPlaySound and modiftying the code to match below:
if (!regexFilter.IsMatch(inputText))
    if (PlayErrorSound)
    e.Handled = true;


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

United Kingdom United Kingdom
No Biography provided

Comments and Discussions

Generaloptimized for filtering every char Pin
jopomo20-Nov-06 4:35
memberjopomo20-Nov-06 4:35 
GeneralBug in filteredTextBox_KeyPress Pin
Perry211-Apr-06 13:10
memberPerry211-Apr-06 13:10 
GeneralWM_PASTE Pin
tonyt9-Oct-05 20:27
membertonyt9-Oct-05 20:27 
GeneralRe: WM_PASTE Pin
[ICR]9-Oct-05 21:20
member[ICR]9-Oct-05 21:20 
GeneralUmm... Pin
The_Mega_ZZTer9-Oct-05 7:45
memberThe_Mega_ZZTer9-Oct-05 7:45 
GeneralRe: Umm... Pin
[ICR]9-Oct-05 7:56
member[ICR]9-Oct-05 7:56 
GeneralRe: Umm... Pin
The_Mega_ZZTer9-Oct-05 7:59
memberThe_Mega_ZZTer9-Oct-05 7:59 
GeneralRe: Umm... Pin
[ICR]9-Oct-05 8:06
member[ICR]9-Oct-05 8:06 
GeneralRe: Umm... Pin
[ICR]9-Oct-05 11:48
member[ICR]9-Oct-05 11:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Posted 9 Oct 2005


13 bookmarked