65.9K
CodeProject 正在变化。 阅读更多。
Home

C#验证TextBox控件

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.55/5 (11投票s)

2002 年 7 月 21 日

2分钟阅读

viewsIcon

405275

downloadIcon

8438

一个具有输入验证功能的TextBox控件,用C#编写。

Sample Image Property Pane Image

引言

在编写一个 C# 小工具时,我将在 CodeProject 上稍后展示,我需要一个具有输入验证功能的 TextBox 控件。 由于我没有在此处找到用 C# 编写的此类控件,因此我编写了自己的控件,并尝试用我的第一篇文章来展示它!

功能

目前,此控件通过将用户输入的字符与包含有效或无效字符的字符串进行比较,执行基本的输入验证。

描述

ValidatingTextBox 类位于 TextBoxExtension.dll 程序集中,在 TextBoxExtension 命名空间中。

ValidatingTextBox 控件的行为由三个属性控制

public string ValidationString{get;set;}

此属性获取或设置用于验证输入的字符串。

public ValidationType ValidationMode{get;set;}

此属性控制提供的 ValidationString 中的字符是包含有效字符还是无效字符。

public bool CaseSensitiveValidation{get;set;}

如果将此属性设置为 true,则大写字母和小写字母将被视为不同的字符。

事件

根据用户操作,控件会触发各种事件

属性更改事件

public event EventHandler ValidationModeChanged;

每当 ValidationMode 属性发生更改时,都会触发此事件。

 public event EventHandler ValidationStringChanged;

每当 ValidationString 更改时,都会触发此事件。

 <code>public event EventHandler CaseSensitiveValidationChanged;

当验证的大小写敏感性发生更改时,会触发此事件。

验证事件

public event EventHandler ValidationSuccessful;

当字符输入成功通过验证时,会触发此事件。

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);
		

当字符验证失败时,会引发此事件。事件处理程序会连同当前的验证模式一起,呈现验证失败的字符(例如,用于错误报告)。

验证过程发生在基类的 WndProc 方法的重写中

在此重写中,拦截 WM_CHAR 消息,并且只有在输入了有效字符时才调用基类的方法。像 Tab、Delete 和 Return 这样的不可显示的键盘输入始终被视为有效。

  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);
      }
    }
		

如果您需要重新验证控件的内容,可以调用

public bool RemoveInvalidChars(){...}

控件的方法,所有无效字符都将被删除。此函数永远不会删除换行符、回车符或制表符。如果删除了任何字符,则返回 true。

本文的示例项目让您可以试用此控件的各项功能。 您可以通过右键单击工具箱并选择自定义(希望这就是 VS .NET 的德语版本中的叫法)来将此控件添加到工具箱中。 然后,您可以将包含我的控件的程序集添加到 .NET 程序集列表中 - 瞧。 如果您发现任何错误或认为此控件有用,请告诉我。

© . All rights reserved.