博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Win Form程序中的输入验证控件

Posted on 2011-10-17 16:00  gczhao  阅读(456)  评论(0编辑  收藏  举报

本文转自:http://www.cnblogs.com/happy5630/articles/1257075.html

 

ASP.NET提供了一个验证用户输入的机制,可以在用户提交数据前,验证他们的输入。然而,在WinForm程序里面,微软却没有提供一个这样的组件。本文的目标是给出一个WinForm的验证控件,并且,你不需要写任何的代码就能做验证。

以前的方案
当我们验证一个控件中的文本,比如验证一个叫txtPassword的TextBox,要求用户输入字母开头,有3-8个数字或字母。我们不得不注册txtPassword的Validating事件:

private void txtPassword_Validating(object sender, CancelEventArgs e)
{
if (string.IsNullOrEmpty(txtPassword.Text))
{
errorProvider1.SetError(txtPassword, "Password required!");
}
else if (!Regex.IsMatch(txtPassword.Text, @"[A-Za-z][A-Za-z0-9]{2,7}"))
{
errorProvider1.SetError(txtPassword, "Password invalid!");
}
else
{
errorProvider1.SetError(txtPassword, null);
}
}

在提交按钮中,需要写如下代码:

 

private void btnOK_Click(object sender, System.EventArgs e)
{
foreach (Control control in this.Controls)
{
// Set focus on control
        control.Focus();
// Validate causes the control's Validating event to be fired,
        // if CausesValidation is True
        if (!Validate())
{
DialogResult = DialogResult.None;
return;
}
}
}


这真是一个很笨的方法,如果你的界面上有很多控件,就会给维护带来很大的麻烦。

背景
我从下面的这篇文章中,得到了不少启迪,你也可以去读一读:
Extending Windows Forms with a Custom Validation Component Library - Michael Weinhardt.

Win Form程序中的输入验证控件

 代码使用
首先创建一个win Form应用程序,接下来按照下面的步骤使用这个控件。

1. 添加控件

在Toolbox上添加Item,并选择Browse,选中Validator.dll控件的链接库。

然后它就被添加到工具栏里了。

如果你已经把验证控件设置了强类型,并把它添加到GAC。你也可以直接从".NET Framework components"中选择加载。


2. 添加并配置组件

拖Validator控件到form上。
其最重要的属性是:
Form: 知道验证控件将要验证的form,它会注册FormClosing事件,在关闭的时候,自动验证。
Mode: 它是一个枚举类型属性,可以是FocusChange和Submit中的一个或组合。FocusChange意味如果验证失败,那么会在那个控件上设置焦点,或移到下一个tab索引控件。Submit意味着当form事件closing时,进行拦截,如果验证失败,阻止关闭。
BlinkRate, BlinkStyle, Icon, RightToLeft:和ErrorProvider属性一样,需要请查看MSDN的帮助文档。

3. 配置文本框和属性

现在,我们假设有3个TextBox和1个提交按钮。

 

Name Text Properties Function
txtName     User name, required input.
txtPassword   PasswordChar = "*" Input password, begins with an alphabet and has 3-8 numbers or alphabets.
txtRePassword   PasswordChar = "*" Re-input password, same as password.
txtSubmit Submit DialogResult = OK Submit and close form.

 

接下来,让我们为这些控件配置验证吧。我们以txtRePassword为主进行演示:
显示一下txtRePassword的属性窗口,你会惊奇地发现多了个目录组Validation:
Type:下拉"Type on validator1",选择Required和Compare

RequiredMessage:填入提示信息"Please input re-password.".
ComparedControl:下拉框中选择,"txtPassword".
CompareOperator:选择"Equal".
CompareMessage:输入"Re-Password not same as password".

其它的属性设置:

Name Validation
txtName Type=Required
txtPassword Type = Required|RegularExpression
RegularExpression = ^[A-Za-Z][A-Za-z0-9]{2,7}$
RegularExpressionOptions = None
txtRePassword Type = Required|Compare
ComparedControl = txtPassword
CompareOperator = Equal

 

测试你的form
运行一下吧,你一定发现了什么不同的地方:)

感谢