EnterpriseLibrary 3.0的验证应用程序块,可以为系统开发提供统一的验证方法,并且和其他程序块一样操作简单,非常实用。
1,使整个程序维持统一的验证风格;
2,验证对象必须是标准的.net数据类型;
3,允许通过配置文件,特性,代码来创建规则;
4,允许对同一个验证对象设置多个验证规则。
EnterpriseLibrary 3.0的验证应用程序块,可以为系统开发提供统一的验证方法,并且和其他程序块一样操作简单,非常实用。
1,使整个程序维持统一的验证风格;
2,验证对象必须是标准的.net数据类型;
3,允许通过配置文件,特性,代码来创建规则;
4,允许对同一个验证对象设置多个验证规则。
先给大家举个具体操作的例子:
1;向系统添加引用:
Microsoft.Practices.EnterpriseLibrary.Validation.dll;
Microsoft.Practices.EnterpriseLibrary.ObjectBuilder.dll
2;根据您的程序类型在下面3个中选择添加引用;
Microsoft.Practices.EnterpriseLibrary.Validation.Integration.WinForms.dll ;
Microsoft.Practices.EnterpriseLibrary.Validation.Integration.AspNet.dll ;
Microsoft.Practices.EnterpriseLibrary.Validation.Integration.WCF.dll ;
3在你的c#代码中使用
using Microsoft.Practices.EnterpriseLibrary.Validation;
using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;
4,编写代码
public class Employee
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
private string _name;
private string _email;
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
[StringLengthValidator(0, 12)] //该属性的字符串长度为0-12;
public string name
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
get
{ return _name; }
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
set
{ this._name = value; }
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
[RegexValidator(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*")] //该属性满足此表达式;
public string email
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
get
{ return _email; }
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
set
{ this._email = value; }
}
}
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
public partial class _Default : System.Web.UI.Page //实际运用
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
protected void Page_Load(object sender, EventArgs e)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
Employee employee = new Employee();
employee.name = "my name is Young.Jiang";
employee.email = "Young18.J#gmail.com";
ValidationResults vrs = Validation.Validate<Employee>(employee); //对employee对象进行验证,返回验证结果。
if (!vrs.IsValid)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
foreach (ValidationResult vr in vrs)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
Response.Write(string.Format("错误位置:{0};原因:{1}<br>", vr.Key, vr.Message));
}
}
}
}
最终显示的结果是:
错误位置:name;原因:The length of the value must fall within the range "0" (Inclusive) - "12" (Inclusive).
错误位置:email;原因:The value must match the regular expression "\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" with options "None".
上例中RegexValidator,StringLengthValidator都是validator中的一种验证类型,除此之外validator还有多种验证类型,下面我们来看看如何通过特性和代码来编写验证规则及如何通过 Tag 和 MessageTemplate来关联验证对象。
ContainsCharactersValidator:验证对象是否包含某些特定字符
属性:CharacterSet:要验证的字符,可以是多个字符组成的字符串;
ContainsCharacters:有any和all两种,any表示如果CharacterSet中某个字符匹配就满足匹配规则,all表示必须完全匹配;
DateTimeRangeValidator 时间范围验证
DomainValidator 域验证,为验证对象设置指定清单
eg. [DomainValidator("young", "jiang", "yang")] :验证对象必须是上述列举字符串的一种
EnumConversionValidator 枚举验证
参数:EnumType
eg. enum Sex {female,male}
[EnumConversionValidator(typeof(Sex))]
NotNullValidator 非空验证
ObjectValidator 对象验证,将提到的验证器作用与一个对象,如果对象为空,将忽略所有验证,
ObjectCollectionValidator 对象集合验证,参数为指定的集合类型
eg. [ObjectCollectionValidator(typeof(sex)]
PropertyComparisonValidator 比较验证
参数:1)比较因子(另一个属性) 2)比较名称 ComparisonOperator,一个枚举
[PropertyComparisonValidator("MinimumBid", ComparisonOperator.GreaterThanEqual)]
要验证对象必须大于等于MinimumBid属性
RangeValidator 范围验证
eg. [RangeValidator(0, RangeBoundaryType.Inclusive, 110,RangeBoundaryType.Inclusive)]
验证在0-110之间,包括0和110
RegexValidator 正则验证
RelativeDateTimeValidator 时间范围验证,
我理解与DateTimeRangeValidator的区别是,DateTimeRangeValidator指定具体的时间范围, RelativeDateTimeValidator与验证对象相关的一个时间范围。
eg.[RelativeDateTimeValidator(-120, DateTimeUnit.Year, -18, DateTimeUnit.Year)]
StringLengthValidator 字符串长度验证
TypeConversionValidator 转换验证
eg. [TypeConversionValidator(typeof(double))] 验证对象需能转换为double型
AndCompositeValidator and验证 几种验证规则必须全部满足
eg. [ValidatorComposition(CompositionType.And)]
[NotNullValidator]
[StringLengthValidator(10)]
验证对象必须同时满足NotNullValidator验证和StringLengthValidator验证
OrCompositeValidator or验证,满足几种验证规则之一即满足验证,可与AndCompositeValidator比较学习
上面列举的所有验证都有一些公共属性来定制验证结果。
MessageTemplate:验证失败后,返回的错误信息。
MessageTemplateResourceName 与 MessageTemplateResourceType从指定模板清单中选择一种模板的名称和类型
Negate:验证取反,bool型,默认为false,不取反
eg. [StringLengthValidator(0,12)]表示验证对象长度在0-12之间,如果在加上Negate=true,表示验证对象长度在0-12之间,则验证失。
Tag :对验证对象分类
Ruleset:为一组规则命名。
实用Self Validation来进行内部验证
用HasSelfValidation 标志需要内部验证的类,实用SelfValidation标注类中需要验证的方法。
[HasSelfValidation]
public class Address
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
{
private string _zipCode;
[StringLengthValidator(1,10)]
public string ZipCode
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
get
{ return _zipCode; }
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
set
{ _zipCode = value; }
}
[SelfValidation]
public void DoValidate(ValidationResults results)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
ValidationResult result1 = new ValidationResult("Error Message", typeof(Address), "","", null);
results.AddResult(result1);
}
}
在实际程序中根据设置的特性来对对象进行验证
Customer customer = new Customer();
ValidationResults results = Validation.Validate<Customer>(customer, customerRuleSetCombo.Text);
页可以实用下面代码
Customer customer = new Customer();
Validator<Customer> validator = ValidationFactory.CreateValidator<Customer>(customerRuleSetCombo.Text);
ValidationResults results = validator.Validate(customer);
在asp.net中实用PropertyProxyValidator进行验证
<asp:TextBox ID="firstNameTextBox" runat="server"></asp:TextBox>
<cc1:propertyproxyvalidator id="firstNameValidator" runat="server"
ControlToValidate="firstNameTextBox"
PropertyName="FirstName"
RulesetName="RuleSetA"
SourceTypeName="ValidationQuickStart.BusinessEntities.Customer">
</cc1:propertyproxyvalidator>
创建型验证规则
Validator<string> emailAddressValidator = new RegExValidator(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
使用RegExValidator来创建一个新验证器emailAddressValidator
Validator shortStringValidator = new AndCompositeValidator(
new NotNullValidator(),
new StringLengthValidator(1, 5));
验证规则继承
Public Class Customer
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
{
[CustomerNameValidator]
public string Name
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
get
{/**//* ... */}
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
set
{/**//* ... */}
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
[DiscountValidator]
public virtual double Discount
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
get
{ /**//* ... */}
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
set
{/**//* ... */}
}
}
public class PreferredCustomer : Customer
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
{
[PreferredDiscountValidator]
public override double Discount
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
get
{/**//* ...*/}
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
set
{ /**//*... */}
}
}
在上面例子中,PreferredCustomer 继承Customer类,也继承了[CustomerNameValidator]验证规则,但用[PreferredDiscountValidator]取代了 [DiscountValidator]验证规则