65.9K
CodeProject is changing. Read more.
Home

Filtered Textbox

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.18/5 (6 votes)

Oct 9, 2005

1 min read

viewsIcon

50644

downloadIcon

514

Demonstrates how to impliment a textbox who's input is regulated via. a regular expression.

Introduction

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)
        SystemSounds.Beep.Play();
    e.Handled = true;
}