Click here to Skip to main content
Email Password   helpLost your password?

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.

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralWhat is the Licensing?
TungstenCoil
13:48 23 Jul '07  
Hi,

Great project! What is your licensing for use of the .dll?

Thanks!
Generalgreat part != validation. great part == windows messages
jhered
8:48 23 Jan '07  
what's great is intercepting wm_char messages... because i've been looking for a way to do this in .Net for accepting text input into XNA/MDX.

Thanks!Cool
Generalvalid text?
Anonymous
16:40 1 Oct '04  
hi,
how do i check to see whether a user has entered text which is a number (double value) instead of any other characters?
thanks!
GeneralRe: valid text?
impro
17:49 1 Oct '04  
You can user Regular Expressions

if (Regex.IsMatch(this.txtCodigo.Text,@"/(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/"))
{
//valid
}
else
{
//Not valid
}
Generalthank
bluebillow
5:46 5 May '03  
that is very good.thanks!
I learing verymore.
Generalwhy override winproc?
Darkmatter
9:48 30 Apr '03  
I am just wondering why winproc was over written rather than some event from the textbox class?

WTF

Darmatter
Generalhelp me,vertically input text
jirigala
20:19 3 Dec '02  
help me,vertically input text
I want a control ,that can vertically input text.
use it input mongol,how can help me,my name is jirigala,
i am from China, my home page

www.mongolmail.com
jirigala@mengguren.com
GeneralRe: help me,vertically input text
maniaug81
21:05 30 Jan '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
maniaug81
22:10 30 Jan '05  
i have find out the solution of ur problem of inputting in vertical format in a text box posted on codeproject on 4th december 2002. if u are still in need of this then just tell me, i will send you the code.

regards
mani

mani


Last Updated 21 Jul 2002 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010