Click here to Skip to main content
15,867,939 members
Articles / Programming Languages / Visual Basic
Article

RegexTextBox: A Windows Control Library

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
4 Jun 2008CPOL3 min read 34.7K   323   20   4
A textbox with regex masking and validation.

Introduction

This single control library is an attempt to fill a void in the basic toolbox of developers. The RegexTextBox is a control that restricts user input and validates that input based on Regular Expressions. The RegexTextBox can be added to the Toolbox, and comes with its own toolbox image.

Prerequisite knowledge

This article assumes that you know how to add a control to your Toolbox.

Background

As a frequent developer of Windows Forms, I find that I often need a textbox that can restrict the input from a user and also validate the input. This is a frequent topic of discussion on forums, and there have been various other posted solutions. However, the scope of those solutions has been limited. For example, you can find a solution for a textbox that restricts input to digits only, or letters only, but what about a textbox that limits input to the digits 1 to 4 and only letters A, C, or F? Enter the power of Regular Expressions to solve this problem and the RegexTextBox.

Using the code

If you are not familiar with Regular Expressions, it is probably time. For a quick introduction and some hands-on experience, why not visit regexlib.com.

The RegexTextBox contains two properties of importance. The first and the most significant property is RegexKeysSet. This property contains the Regular Expression that is used to identify which keypress to accept and which to reject.

As an example, let's examine the case where we want the user to enter a decimal number. In this case, we wish to accept the following keys: 0 to 9 and the decimal.

If your RegexTextBox was named rgxTextbox, then we would set the RegexKeysSet like so:

VB
rgxTextbox.RegexKeysSet = "^[0-9\.]$"

Once that property is set, the RegexTextBox will only allow those keys to be entered. In order to accomplish this, the OnKeypress event is overridden like so:

VB
Protected Overrides Sub OnKeypress(ByVal e As System.Windows.Forms.KeyPressEventArgs)  
    Dim keyInput As String = e.KeyChar.ToString() 
    Dim ValidInput As Boolean = True
        If [Char].IsLetterOrDigit(e.KeyChar) Then
            ValidInput = Regex.IsMatch(keyInput, RegexKeysSet)
        ElseIf [Char].IsPunctuation(e.KeyChar) Then
            ValidInput = Regex.IsMatch(keyInput, RegexKeysSet)
        ElseIf [Char].IsSeparator(e.KeyChar) Then
            ValidInput = Regex.IsMatch(keyInput, RegexKeysSet)
        ElseIf [Char].IsSymbol(e.KeyChar) Then
            ValidInput = Regex.IsMatch(keyInput, RegexKeysSet)
        ElseIf [Char].IsWhiteSpace(e.KeyChar) Then
            ValidInput = Regex.IsMatch(keyInput, RegexKeysSet)
        End If

        'if the keyInput is not in RegexKeysSet then consume the key
        If Not ValidInput Then e.Handled = True
End Sub

However, this does not prevent the user from entering invalid text. It just masks the input. Using the above example, the following could be entered into the RegexTextBox:

"00.12.588.12", "145",  ".65"

This is why there is a second property called RegexValidText. Using the above example again, if we want to test for a valid decimal input, we would set the RegexValidText property and call the IsValidText method.

Set the RegexValidText property:

VB
rgxTextbox.RegexValidText = "^\d*\.?\d*$"

The following example will change the background color of the RegexTextBox to indicate valid input:

VB
Private Sub rgxTextBox_TextChanged(ByVal sender As System.Object, _ 
            ByVal e As System.EventArgs) Handles rgxTextBox.TextChanged
    If rgxTextBox.IsValidText Then
        rgxTextBox.BackColor = Color.Green
    Else
        rgxTextBox.BackColor = Color.Red
    End If
End Sub

If you need to prevent invalid text from being entered, then you will need to add some of your own code. This passive method of validation allows me to choose what I want to do with invalid input and when to test for it.

Points of Interest

The functional limitations of this control are limited only by your creativity with Regular Expressions. Even if you aren't a master of Regular Expressions, you can always search for an expression that will suit your needs and then write the expression for the RegexKeysSet yourself (which is relatively simple once you get the hang of it).

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Canada Canada
Casual programmer intersted in creating simple windows games (mostly remakes of classic Dos or Windows 3.1 games)

Comments and Discussions

 
GeneralPasted Text Pin
arc207223-Mar-11 4:59
arc207223-Mar-11 4:59 
Generaltivir Pin
tivir20-Feb-11 5:13
tivir20-Feb-11 5:13 
GeneralNice and useful !!! Pin
Ashutosh Phoujdar16-Jun-08 22:29
Ashutosh Phoujdar16-Jun-08 22:29 
It is really nice, However there are couple of turnaround can be done :

1) Catch the KeyPress event for the controls Inquire the keys pressed and supress any keys that are not matching with Regex pattern, Simple code snippet for that as follows

Private Sub TextBox1_Press(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyUp

'' Perform validation logic using text property, If validation failed
If Not(RegEx.IsMatch(TextBox1.text,RegExset)) Then
 ' Stop the character from being entered into the control since it is non-numerical.
        e.Handled = True
End If

End Sub


2) Replace the TextBox with the MaskedTextBox. Then add a mask limiting only some pattern to be entered.


Thanks for sharing. Smile | :)

dnpro
"Very bad programmer"

GeneralRe: Nice and useful !!! Pin
MijaeDjinn17-Jun-08 9:54
MijaeDjinn17-Jun-08 9:54 

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.