Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

A Custom TextBox with Regular Expression Validation Using MC++

0.00/5 (No votes)
4 Oct 2004 1  
A custom TextBox with input validation written in VC++.NET, also walks you through the steps needed to build your own custom controls

1. Introduction

This article is motivated by the following situation: suppose we are developing some application for the user and in the application's GUI, we are using several TextBox controls to accept user's inputs. Quite often, these inputs should follow some specific format. For instance, the zip code we want from the user has to be something like "30022"; the address should look like "2025 roadName Rd" or "931 roadName"; the email account the user provides has to have the format "name@something.com", etc. We can certainly add different validation code after accepting the text from each TextBox control, but a better solution is to have a TextBox control which uses regular expression to validate the user input, since regular expression seems to be powerful enough to describe almost all the formats we encounter in our daily life. All we need to do is to specify a regular expression in the TextBox's regularExpression property so it can verify the user input for us - imagine how many lines of code you need to write in order to validate a legal email address if there were no regular expressions!

If you are developing ASP.NET applications, there is a control already uses regular expression to validate inputs. However, for Windows Forms, the TextBox control does not have a regularExpression property thus does not offer this validation functionality. Therefore, a solution is to build our own custom TextBox control which has regularExpression as a property and validates the inputs by using this regular expression. After building it, we can add it to the ToolBox in the IDE and we would then use it whenever we need to validate the input text. This is what we are going to accomplish in this article: in the next several sections, I will walk though the steps that are needed to build this custom control and a small testing project is also provided to see how we can use the new control just built.

There are several articles from other CPians discussing the same issue, however, none of these controls is written in VC++.NET and none of these articles walks though the steps that are needed to accomplish this - and it seems that these steps will be helpful if the readers want to make improvements of their own. In the next section, I will show all the steps of building this custom control and all the necessary code that you need to add to the control. In the last section I will discuss a simple testing project and the regular expressions that I used to validate the sample inputs.

2. Step By Step: Building the Custom TextBox Control

In this section, the steps that are needed to build the custom control are described, this custom control directly inheriates from the original TextBox control that is provided in the .NET ToolBox. If you are familiar with these steps, you can skip this section and directly download the .dll file that is provided with this article and hopefully, you decide to use it in your own development.

Step 1: create a new project whose type is Windows Control Library(.NET), name this project ValidatingTextBox (I am not good at naming stuff, so use whatever name you like!).

Notice we are selecting the project type to be Control Library, this will give us a .dll file, in this case, it will be a generic custom control that we can use in our other applications.

Step 2: open ValidatingTextBoxControl.h, find the following line:

public __gc class ValidatingTextBoxControl : 
   public System::Windows::Forms::UserControl

change the UserControl to TextBox, so the above line looks like this:

public __gc class ValidatingTextBoxControl : 
   public System::Windows::Forms::TextBox

This is necessary, since our custom control is still a TextBox, with a validating functionality using regular expression. This change will make sure that ValidatingTextBoxControl directly inheriates from TextBox.

Step 3: since we are going to use regular expression support from .NET, in the using namespace section, add the following line:

using namespace System::Text::RegularExpressions;

Step 4: add the following private member and the necessary properties:

private:
  String* regularExpression;

public:
  __property String* get_RegularExpression()
  {
    return regularExpression;
  }

  __property void set_RegularExpression(String* regExpValue)
  {
    regularExpression = regExpValue;
  }

This will make sure when we use ValidatingTextBoxControl in our application, we will see a RegularExpression item in its Properties window, and we can edit this property just like we can edit any other property of the control.

Step 5: since we added a private member regularExpression, we need to make some changes to the constructor of the ValidatingTextBoxControl class:

public:
  ValidatingTextBoxControl(void)  
  {
    InitializeComponent();
    this->regularExpression = 0;
    this->CausesValidation = true;
  }

Step 6: now it is the real important part: the validation part. Add the following private member function:

private: bool isValid()
{
   if ( regularExpression == 0 ) return true;
   Match* theMatch = Regex::Match(this->Text,regularExpression);
   if ( theMatch->Success && theMatch->Length == this->Text->Length )
      return true;
   else return false;
}

Clearly, if the regularExpression property is never edited in the Properties window, then the validation always returns a true value, otherwise, Regex's static method Match() will be used to test if the user's input satisfies the format that is specified by the regularExpression. Also, the comparison of the Length is important: a regularExpression whose value is "\d{5}" (for the zip code) will not only match 30022, but will also match 30022abc. To avoid this, we need the Length comparison.

Step 7: we need to override the OnValidating(CancelEventArg* e) in the base class. This is the place where the above isValid() function gets called:

protected: void OnValidating(CancelEventArgs* e)
{
   if ( isValid() == false )
   {
      // Cancel the event and select the text to be corrected by the user.

      e->Cancel = true;
      MessageBox::Show( String::Concat(S"\"", this->Name, S"\" is not correct"),
                        S"Error: invalide input value",
                        MessageBoxButtons::OK,MessageBoxIcon::Error);
      return;
   }
   __super::OnValidating(e);
}

This will also make sure that if the user's input is not correct, the application will not continue and a simple message will pop-up to show the user what is wrong and what will be the correct format (you might want to change this to make it disappear or more useful).

Step 8 (last step): now we can build the project, and if everything is fine, we will get a ValidatingTextBox.dll, and this is the final product: it is a generic custom TextBox control and it can use a given regular expression to validate the user input.

In the next section, a small testing project is presented to show how to "insert" this newly created control into the ToolBox in .NET's IDE and how can one use it. In fact, it is quite simple: you use it just like you use any other control!

3. Testing Example

Let us follow these steps to build a sample testing project to see how we can use our newly created control:

Step 1: create a new project of type Windows Forms Application(.NET), name this project testValidatingTextBox.

Step 2: import ValidatingTextBox: in the new project, right click in the ToolBox area and select Add/Remore Items... menu. A dialog will appear and in this dialog, select the .NET Framework Components tab. Click the Browse... button to locate the ValidatingTextBox.dll we just built, open it. This will bring this custom control into the component list and make sure the checkbox next to this control is checked. Click OK. Now you will see the ValidatingTextBoxControl appears in the ToolBox list and it can be added to the form just like any other control.

Step 3: build a simple GUI which has the following 3 input text boxes: the zip code, the address and the email account (see the screen shot at the beginning of this article). Notice the TextBox control we are using in this simple GUI is the ValidatingTextBoxControl that we just built in Section 2, and we can use it just like we use the original TextBox contorl. However, the only special part of it (and it is the reason why we built it) is that in order to validate the user input, we need to specify the RegularExpression property for each of these 3 inputs: the screen shot at the beginning of this article shows the regular expression that we use for the address input:

^[0-9]+\s+([a-zA-Z]+|[a-zA-Z]+\s[a-zA-Z]+)$

This regular expression says the correct address has to start with at least 1 digit number (from 0 to 9), followed by at least one space (can have more), and then there should be at least one letter, or, after this letter(s), there can be a single space, followed by at least another letter. So all these address are the correct ones: 123 peachtree, or, 123 peachtree rd, but the following are not acceptable: Pearchtree 123, 123, etc.

Accordingly, let us specify the regular expression for the zip code and the email account. For zip code, we use \d{5}, this says that the zip code has to be exactly 5 digits; for email account, we use [0-9a-zA-Z]+@[0-9a-zA-Z]+\.com, this says the email account has to start with digit or letter, followed by a @ and then some other digits or letters, followed by .com (you can also allow .net, .org, etc.)

Step 4: build the project and try it out. Now you can start to input text in the text boxes. If you provide the wrong input, a message box will show up and tell you the correct format for that particular text box.

These are the basic steps of how to import the custom control and how to use it in our development work. A problem for regular expression is that if you specify a wrong expression, the control will not tell you this - it simply does not do the job and it will also prevent you from continuing your input. Therefore, it is now up to you to provide a correct expression!

4. That's it!

This article presents a custom TextBox control which has a RegularExpression property that you can use to validate any user input text. In this article, we walk though the steps that are needed to build a custom control and we also build a testing project to show how to import the custom control and how to use it in your applications. You can directly download the .dll file and use the control in your work, but you are more than welcome to download the source code so you can make changes and add more features to it, and I certainly look forward to your improvements and commends.

License

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