Click here to Skip to main content
15,886,796 members
Articles / Programming Languages / C#
Article

C# Validating TextBox Control

Rate me:
Please Sign up or sign in to vote.
3.55/5 (11 votes)
20 Jul 20022 min read 403K   8.4K   77   11
A TextBox Control with Input Validation written in C#

Sample Image Property Pane Image

Introduction

While writing a little tool in C# which I will present here at CodeProject some time in the future I needed a TextBox Control with the ability of input validation. Because I didn't find a control like this written in C# here at CodeProject I wrote my own and try to present it with my first article!

Capabilities

Right now this control performs basic input validation of the characters entered by the user by comparing them to a string containing valid or invalid characters.

Description

The ValidatingTextBox class resides in the TextBoxExtension.dll assembly in the TextBoxExtension namespace.

The behaviour of the ValidatingTextBox control is controlled by three properties:

public string ValidationString{get;set;}

This property gets or sets the string to validate the input against.

public ValidationType ValidationMode{get;set;}

This property controls wether the characters in the provided ValidationString contain the valid chars or the invalid chars.

public bool CaseSensitiveValidation{get;set;}

If this property is set to true uppercase letters are treated differently than lowercase ones.

Events

Depending on user action various events are fired by the control:

Property-changed events:

public event EventHandler ValidationModeChanged;

This event gets fired whenever the ValidationMode Property has been changed.

 public event EventHandler ValidationStringChanged;

This event gets fired whenever the ValidationString changed.

 <code>public event EventHandler CaseSensitiveValidationChanged;

Whenever the case sensitivity of the validation is altered this event gets fired.

Validation Events:

public event EventHandler ValidationSuccessful;

Whenever a character input has been successfully validated this event gets fired.

public event CharValidationFailedEventHandler CharValidationFailed;

public class CharValidationFailedEventArgs : EventArgs
{
  public CharValidationFailedEventArgs(ValidationType mode, char failed)
  {
    currentValidationMode = mode;
    failedChar = failed;
  }

  // Holds the char that failed validation
  private char failedChar;

  // Holds the validation mode
  private ValidationType currentValidationMode;

  // This property gets the char that failed validation
  public char FailedChar
  {
    get
    {
      return failedChar;
    }
  }

  // This property gets the current Validation mode
  public ValidationType CurrentValidationMode
  {
    get
    {
      return currentValidationMode;
    }
  }
}

	

public delegate void CharValidationFailedEventHandler(object sender,
                                        CharValidationFailedEventArgs e);

This event is raised whenever a char failed validation. The event handler presents the char that failed validation (f.e. for error reporting) along with the current validation mode.

The validation process takes place in an override of the WndProc method of the base class:

In this override WM_CHAR messages are intercepted and the method of the base class is only called when a valid char has been entered. Non displayable keyboard input like Tab, Delete and Return are always treated as valid:

private const int WM_CHAR = 0x0102;

private const int VK_BACK = 0x08;

private const int VK_TAB = 0x09;

private const int VK_CLEAR = 0x0C;

private const int VK_RETURN = 0x0D;

protected override void WndProc(ref Message message)
{
    if(message.Msg == WM_CHAR)
    {
      char cTest = (char)message.WParam;
      string sTest;//needed for case insensitive validation
      string sValidate;//needed for case insensitive validation
      if(caseSensitiveValidation)
      {
        sTest = cTest.ToString();
        sValidate = validationString;
      }
      else //Uppercase both strings to neutralize casing
      {
        sTest = cTest.ToString().ToUpper();
        sValidate = validationString.ToUpper();
      }
      switch(cTest)//some characters always pass through
      {
        case (char)VK_BACK:
        case (char)VK_CLEAR:
        case (char)VK_RETURN:
        case (char)VK_TAB:
          base.WndProc(ref message);
          if(CharValidationSuccessful!=null)
          {
            EventArgs args = new EventArgs();
            CharValidationSuccessful(this,args);
          }
          return;
      }
      //start validation
      if(validationMode == ValidationType.ValidateAgainstValid)
      {
        if(sValidate.IndexOf(sTest)<0)//char not present in validation string
        {
          if(CharValidationFailed!=null)
          {
            CharValidationFailedEventArgs args =
              new CharValidationFailedEventArgs(validationMode,cTest);
            CharValidationFailed(this,args);
          }
          return;
        }
        else//valid char
        {
          base.WndProc(ref message);
          if(CharValidationSuccessful!=null)
          {
            EventArgs args = new EventArgs();
            CharValidationSuccessful(this,args);
          }
          return;
        }
      }
      else //ValidationString contains all invalid chars
      {
        if(sValidate.IndexOf(sTest)<0)//valid char
        {
          if(CharValidationSuccessful!=null)
          {
            EventArgs args = new EventArgs();
            CharValidationSuccessful(this,args);
          }
        base.WndProc(ref message);
        return;
        }
        else//char present in invalidation string
        {
          if(CharValidationFailed!=null)
          {
            CharValidationFailedEventArgs args =
              new CharValidationFailedEventArgs(validationMode,cTest);
            CharValidationFailed(this,args);
          }
          return;
        }
      }
    }
    else //other than WM_CHAR message
    {
      base.WndProc(ref message);
    }
  }

 If you have to revalidate the content of the control you can call the

public bool RemoveInvalidChars(){...}

method of the control and all invalid characters will be removed. This function never removes linefeed, carriage return or tabs. It returns true if any chars have been removed.

The sample project for this article lets you play around with the features of this control. You can add this control to your toolbox by right clicking on the toolbox and selecting customize (hope that's how it is called as I have the german version of VS .NET). Then you can add the assembly containing my control to the list of .NET assemblies - et voila. Please let me know if you find a bug or think that this control is useful.

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


Written By
Austria Austria
After completing my masters in Developmental Genetics at NYU now working on my Phd in Neurobiology back in Europe.
Programming in (Visual) C++ and .NET in my sparetime (I just love the academic license program Smile | :) )

Comments and Discussions

 
QuestionThanksss Pin
Usman59926-Jun-12 20:16
Usman59926-Jun-12 20:16 
QuestionCompatibility Pin
pemola9-Feb-11 21:30
pemola9-Feb-11 21:30 
QuestionWhat is the Licensing? Pin
TungstenCoil23-Jul-07 12:48
TungstenCoil23-Jul-07 12:48 
Generalgreat part != validation. great part == windows messages Pin
jhered23-Jan-07 7:48
jhered23-Jan-07 7:48 
Questionvalid text? Pin
Anonymous1-Oct-04 15:40
Anonymous1-Oct-04 15:40 
AnswerRe: valid text? Pin
impro1-Oct-04 16:49
impro1-Oct-04 16:49 
Generalthank Pin
bluebillow5-May-03 4:46
bluebillow5-May-03 4:46 
Questionwhy override winproc? Pin
Darkmatter30-Apr-03 8:48
Darkmatter30-Apr-03 8:48 
Generalhelp me,vertically input text Pin
jirigala3-Dec-02 19:19
jirigala3-Dec-02 19:19 
GeneralRe: help me,vertically input text Pin
maniaug8130-Jan-05 20:05
maniaug8130-Jan-05 20:05 
hi jirigala, this is mani from india.
to take input in a vertical format u can use vbCrLf constant on the key press event of a text box. i have written this code in VB6.0. this will take the input in vertical format.
steps:
1 place a text box control and set multiline property to true.
2. write the following code on the key press event of the text box

Text1.Text = vbCrLf & Text1.Text & vbCrLf

now when u enter text in the text box it will take it in vertical format.

if u still encounter any problem u can mail me at
manish@tvtworld.com,
maniaug81@rediffmail.com


mani
GeneralRe: help me,vertically input text Pin
maniaug8130-Jan-05 21:10
maniaug8130-Jan-05 21:10 

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.