引入RequiredFieldValidator
有了上面的设计思路,现在要来点真的了。让我们从最简单的验证情形开始:RequiredFieldValidator。
建立一个Component类,名称为RequiredFieldValidator,其接口应当与ASP.NET中的对应类相同:
public partial class RequiredFieldValidator : Component
{
string ControlToValidate { get; set;}
string ErrorMessage { get; set;}
string InitialValue { get; set;}
bool IsValid { get; set;}
void Validate();
}
在ASP.NET中,ControlToValidate是字符串类型的,这种间接的做法在基于请求、无状态的Web应用程序中是必要的。但在Windows Forms中我们则不必这么做,我们可以直接引用控件。同时,我们要在内部使用ErrorProvider组件,所以为其添加一个Icon属性:下面是每个成员的含义:
![]()
成员 描述
![]()
ControlToValidate 指定要验证的控件
![]()
ErrorMessage 控件未通过验证时显式的信息。
![]()
InitialValue 某些情况下,控件的默认值用作提示,如”请选择种类”,这时必填项意味着必须与默认值不同。此时用InitialValue。
![]()
IsValid 在调用Validate方法后报告控件的数据是否有效,默认为true。
![]()
Validate 验证指定控件的值,并设置IsValid。
![]()
public partial class RequiredFieldValidator : Component
{
…
Control ControlToValidate { get; set;}
Icon Icon { get; set;}
…
}
