且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Enterprise Library 4.1学习笔记5----实体验证程序块

更新时间:2022-08-13 16:04:46

实体验证的作用简单来讲,就是从服务端对数据进行验证。(特别是对数据安全性要求比较高的应用,这是十分必要的)

废话不说了,直接讲下使用步骤:(因为我是做web开发的,主要是讲解asp.net环境中的使用)

1.先添加Microsoft.Practices.EnterpriseLibrary.Validation.dll的引用

2.最基本的使用方法(也是我最不喜欢的一种方式),直接在实体类上通过添加特性实现

实体类如下:

public class Person
{       

    [StringLengthValidator(
212, MessageTemplate = "请输入2-12位长度的字符")]          
    
public string Name
    {
        
set;
        
get;
    }

    [RegexValidator(
@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", MessageTemplate = "请输入有效的Email地址")]
    
public string Email
    {
        
set;
        
get;
    }
}
该方式必须在原有代码几乎每个字段上都要修改,而且这种硬编码的写法比较晕(何况对于linq to sql这类东东,修改dbml后用户所做的修改都会丢失)
 
 
3.然后就可以验证了,代码如下:
using System;
using Microsoft.Practices.EnterpriseLibrary.Validation;
using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;

protected void Page_Load(object sender, EventArgs e)
{
    Person _p 
= new Person() { Name = "1", Email = "jimmy.yang#126.com" };

    ValidationResults _results 
= Validation.Validate<Person>(_p); 
    
    
if (!_results.IsValid)
    {
    
foreach (ValidationResult vr in _results)
    {
        Response.Write(
string.Format("错误位置:{0};原因:{1}<br>", vr.Key, vr.Message));
    }
    }
}
对于步骤2中提到的不便之处,幸好EnLib还提供了另一种方式,允许用户把验证规则放在配置文件中,步骤如下:
(a)先在web.config上右击,选择Edit Enterprise Libaray Configuration
Enterprise Library 4.1学习笔记5----实体验证程序块
(b)新建一个Validataion Application Block
Enterprise Library 4.1学习笔记5----实体验证程序块
(c)new-->Type-->Load From File... 选择实体类所在的DLL(如果实体类没有分层构架,先把项目编译一下,直接选择项目bin目录下的dll)
不过在使用过程中,发现一个bug:如果进行这一步前未编译生成dll,或者进到这一步后,又修改了实体类,配置工具好象反射时,始终不能刷新出最新的实体类,解决办法:关掉vs,重新打开再选择dll就正常了,不知道这是不是我机器上的个别现象
Enterprise Library 4.1学习笔记5----实体验证程序块
Enterprise Library 4.1学习笔记5----实体验证程序块
 
(d)new-->Rule Set --> new --> Choose Members-->选择要验证的成员
Enterprise Library 4.1学习笔记5----实体验证程序块
 
 
(e)添加验证规则
Enterprise Library 4.1学习笔记5----实体验证程序块
 
(f)设置Person的默认规则
Enterprise Library 4.1学习笔记5----实体验证程序块
Ok了,这下所有验证规则都被放到web.config中了,以下是web.config中的相关节点
<validation>
    
<type defaultRuleset="Rule Set" assemblyName="ValidateTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
      name
="ValidateTest.Person">
      
<ruleset name="Rule Set">
        
<properties>
          
<property name="Name">
            
<validator negated="false" messageTemplate="请输入名字" messageTemplateResourceName=""
              messageTemplateResourceType
="" tag="" type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.NotNullValidator, 
Microsoft.Practices.EnterpriseLibrary.Validation, Version=4.1.0.0, Culture=neutral"

              name
="Not Null Validator" />
            
<validator lowerBound="2" lowerBoundType="Ignore" upperBound="12"
              upperBoundType
="Inclusive" negated="false" messageTemplate="名字必须是2到12个字符"
              messageTemplateResourceName
="" messageTemplateResourceType=""
              tag
="" type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.StringLengthValidator, Microsoft.Practices.EnterpriseLibrary.Validation, 
Version=4.1.0.0, Culture=neutral"

              name
="String Length Validator" />
          
</property>
          
<property name="Email">
            
<validator pattern="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
              options
="None" patternResourceName="" patternResourceType=""
              messageTemplate
="请输入有效的电子邮件地址" messageTemplateResourceName=""
              messageTemplateResourceType
="" tag="" type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.RegexValidator, 
Microsoft.Practices.EnterpriseLibrary.Validation, Version=4.1.0.0, Culture=neutral"

              name
="Regex Validator" />
          
</property>
        
</properties>
      
</ruleset>
    
</type>
  
</validation>
以后要修改验证规则,只需要修改web.config即可,相对更灵活一些,但是这样有一个问题,随着要验证的类越来越多,web.config会越来越庞大,其实可以把验证规则单独放到另一个文件里,只需要在web.config上做些修改即可,注意下面的高亮部分
<configuration>
  
<configSections>   
    
<section name="enterpriseLibrary.ConfigurationSource" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ConfigurationSourceSection, Microsoft.Practices.EnterpriseLibrary.Common, Version=4.1.0.0, Culture=neutral" />
    Enterprise Library 4.1学习笔记5----实体验证程序块
  
</configSections>
  
<enterpriseLibrary.ConfigurationSource selectedSource="File Configuration Source">
    
<sources>
      
<add name="File Configuration Source" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.FileConfigurationSource, Microsoft.Practices.EnterpriseLibrary.Common" filePath="config\validate.config"/>
    
</sources>
  
</enterpriseLibrary.ConfigurationSource>
Enterprise Library 4.1学习笔记5----实体验证程序块
上面第二段中的filePath=... 即表示把验证规则放到config目录下的validate.config中
 
接下来直接新建一个config目录,然后把validate.config放在里面就可以了,validate.config内容如下:
<configuration>
  
<configSections>
    
<section name="validation" type="Microsoft.Practices.EnterpriseLibrary.Validation.Configuration.ValidationSettings, Microsoft.Practices.EnterpriseLibrary.Validation, Version=4.1.0.0, Culture=neutral" />
    
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=4.1.0.0, Culture=neutral" />
  
</configSections>
  
<validation>
    
<type defaultRuleset="Rule Set" assemblyName="ValidateTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
      name
="ValidateTest.Person">
      
<ruleset name="Rule Set">
        
<properties>
          
<property name="Email">
            
<validator pattern="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
              options
="None" patternResourceName="" patternResourceType=""
              messageTemplate
="请输入正确的电子邮件地址" messageTemplateResourceName=""
              messageTemplateResourceType
="" tag="" type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.RegexValidator, Microsoft.Practices.EnterpriseLibrary.Validation, Version=4.1.0.0, Culture=neutral"
              name
="Regex Validator" />
          
</property>
          
<property name="Name">
            
<validator lowerBound="2" lowerBoundType="Ignore" upperBound="12"
              upperBoundType
="Inclusive" negated="true" messageTemplate="名字长度为2-12个字符"
              messageTemplateResourceName
="" messageTemplateResourceType=""
              tag
="" type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.StringLengthValidator, Microsoft.Practices.EnterpriseLibrary.Validation, Version=4.1.0.0, Culture=neutral"
              name
="String Length Validator" />
          
</property>
        
</properties>
      
</ruleset>
    
</type>
  
</validation>
</configuration>
最后再讲一点废话,QuickStarts中有一个关于asp.net的验证示例,里面的效果类似于常规的验证控件,不过是要页面提交后,由服务端再返回的,个人觉得这样效率太低,我倾向于先在页面上做客户端验证并给出相关出错提示,然后再到服务端代码里用文中所提的方法来验证,所以这个示例涉及的内容就不准备研究了,大家有兴趣的话,可以自行去look look这个例子