Demo3 使用客户自定义验证
客户自定义验证是程序开发人员对Validation Application Block 的功能的扩展。
任务1 :搭建用于验证的运行环境
1. 新建项目ValidationApp.CustomerValidation ,右键单击解决方案,指向“添加“,选择“新建项目”,在名称栏里输入ValidationApp.CustomerValidation 如图3.1
图3.1 新建项目
2. 添加引用,如前面的实验一样,添加Microsoft.Practices.EnterpriseLibrary.Validation 的引用。
3. 删除项目ValidationApp.CustomerValidation 默认产生的文件类文件Class1 。
任务2 :添加自定义的验证类。
这里所指的自定义验证类是继承于Validator 类的,并且重载了Validator 类的一些方法。
1. 增加一个新类IDValidator 。右键单击项目ValidationApp.CustomerValidation ,指向“添加”,选择“新建项”。然后,选择“类”,在名称栏输入IDValidator, 如图3.2
图3.2 添加类文件
2. 使用Using 语句向 IDValidator 类添加必要的引用。
using System.Text.RegularExpressions;
using Microsoft.Practices.EnterpriseLibrary.Validation;
using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;
3. 向IDValidation 类添加如下代码。主要定义了两个构造函数和一个DoValidate 重载函数。这些代码可以根据验证的需要改动,是自己定义的。
public class IDValidator :Validator <string >
{
public IDValidator(string tag)
: this (tag, false )
{ }
public IDValidator(string tag, bool ignoreHypens)
: base (string .Empty, tag)
{
this .ignoreHypens = ignoreHypens;
}
private bool ignoreHypens;
protected override string DefaultMessageTemplate
{
get { throw new NotImplementedException (); }
}
static Regex IDRegex = new Regex (@"^[0-9]*[1-9][0-9]*$" );
protected override void DoValidate(string objectToValidate, object currentTarget, string key, ValidationResults validationResults)
{
Match match = IDRegex.Match(objectToValidate);
if ((objectToValidate.Length <0)||(objectToValidate.Length >= 18))
{
if (!match.Success)
{
LogValidationResult(validationResults, " 身份证号必须是数字" , currentTarget, key);
}
}
else
{
LogValidationResult(validationResults, " 身份证号码必须是18 位" , currentTarget, key);
}
}
}
任务3 :添加验证属性。
1. 向IDValiation.CustomerValidation 项目添加新类IDValidatorAttribute 。
2. 添加引用。
using Microsoft.Practices.EnterpriseLibrary.Validation;
using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;
3. 按照下面的格式添加代码。
public class IDValidatorAttribute :ValidatorAttribute
{
protected override Validator DoCreateValidator(Type targetType)
{
return new IDValidator (this .Tag);
}
}
任务4 :在项目中使用自定义验证
通过以上实验的配置。现在,我们就可以像使用Validation Application Block 自带的验证方法一样使用[IDValidator] 。不过,本例的其他的验证还是需要配置的,这里就不一一介绍了。下面我们开始使用[IDValidator] 。
1. 在ValidationApp.UserValidation 项目中添加对ValidationApp.Customer 项目的引用。展开ValidationApp.UserValidation 项目的“引用文件夹”,右键单击“引用”,选择“添加引用”,然后指向“项目”菜单,选择ValidationApp.Customer 项目,单击“添加”。
2. 打开User.cs 文件。
3. 使用using 指令添加引用。
using ValidationApp.CustomerValidation;
4. 更新User.cs 文件。
public class User
{
public string UserName{ get ; set ; }
public string password{ get ; set ; }
[IDValidator ]
public string IDcard{ get ; set ; }
public string email{ get ; set ; }
}
任务5 :验证。