【IT168技术文档】
在Enterprise Library 3.0 December 2006 CTP版中,加入了一个新的成员Validation Application Block,用来实现对业务对象的验证。它支持两种方式的验证,通过特性Attribute和通过配置文件,但是在最新版本中并没有提供配置的设计时支持,我们只能通过手动去修改配置文件来实现,所以本文主要看一下通过Attribute来实现验证。
主要内容
1.通过ValidationFactory创建验证器
2.通过外观类实现验证
一.概述
在Enterprise Library 3.0 December 2006 CTP版中,加入了一个新的成员Validation Application Block,用来实现对业务对象的验证。它支持两种方式的验证,通过特性Attribute和通过配置文件,但是在最新版本中并没有提供配置的设计时支持,我们只能通过手动去修改配置文件来实现,所以本文主要看一下通过Attribute来实现验证。
二.通过ValidationFactory创建验证器
Validation Application Block沿用了其他应用程序块的一贯做法,使用相同的操作模式,为我们提供了一个ValidationFactory的工厂,用来创建验证器。首先我们编写一个简单的业务对象类:
这只是一个普通的业务实体类,现在我们要验证它的姓名属性不能为空,且长度在1到50之间,年龄字段在0到200之间,加上如下Attribute:public class User { private String _name; private int _age; public String Name { get { return _name; } set { _name = value; } } public int Age { get { return _age; } set { _age = value; } } }
public class User { private String _name; private int _age; [NotNullValidator] [StringLengthValidator(1,50)] public String Name { get { return _name; } set { _name = value; } } [Int32RangeValidator(0,200)] public int Age { get { return _age; } set { _age = value; } } }