Enterprise libraray3.0之一-------Validation Application Block

来源:互联网 发布:linux phpmyadmin配置 编辑:程序博客网 时间:2024/04/28 06:30

今天闲着没事,看了看Enterprise library 3.0,下载的版本应该是april 2007,反正在官网上下载的最新版本,按照TerryLee及其几篇英文文档做了一下“Validation Application Block”

刚装上一用还真的比较爽,现在这个版本微软已经将提供的工具与vs2005进行集成,可以在配置文件上右键直接打开配置文件进行编辑修改了。

Validation Application Block主要提供了两种验证模式,一种就是直接在实体类中进行配置验证属性;另一种就是通过配置文件(操作步骤请参考TerryLee的博客,上面有图片很清楚的)。

第一种方法:

类代码

        private string _userName;

        [NotNullValidator()]

        [StringLengthValidator(1, 50)]

        public string UserName

        {

            get { return _userName; }

            set { _userName = value; }

        }

        private int _age;

        [RangeValidator(18, RangeBoundaryType.Inclusive, 50, RangeBoundaryType.Inclusive)]

        // Inclusive包含边界

        public int Age

        {

            get { return _age; }

            set { _age = value; }

        }

        private string _email;

        [NotNullValidator]

        public string Email

        {

            get { return _email; }

            set { _email = value; }

        }

 

 

进行验证的代码:

Users user = new Users();

        user.Age = int.Parse(TextBox2.Text);

        user.Email = TextBox3.Text;

        user.UserName = TextBox1.Text;

        Validator<Users> userValidators = ValidationFactory.CreateValidator<Users>();

        ValidationResults results = userValidators.Validate(user);

        Response.Write(results.IsValid.ToString());

        StringBuilder sb = new StringBuilder();

        foreach (ValidationResult result in results)

        {

 

            sb.Append(string.Format("字段:{0}-出错信息:{1}", result.Key.ToString(), result.Message.ToString()) + "<br/>");

 

        }

        Label1.Text = sb.ToString();

 

 

第二种方法:

需要一个类库工程,添加引用

用工具打开web.config文件,新建一个Validation Application Block,然后一步一步的按照Terrylee大哥博客上的图片进行配置就OK了。

唯一值得注意的是要设置DefaultRule,我就是没有设置这个属性,找了半天原因的。

类库文件就不贴了,比上面的类文件还简单,不需要设置哪些验证属性,只是一个很普通的类文件。

web.config的全部源代码

<?xml version="1.0" encoding="utf-8"?>

<!--

    注意: 除了手动编辑此文件以外,您还可以使用

    Web 管理工具来配置应用程序的设置。可以使用 Visual Studio 中的

     网站”->“Asp.Net 配置选项。

    设置和注释的完整列表在

    machine.config.comments 中,该文件通常位于

    /Windows/Microsoft.Net/Framework/v2.x/Config

-->

<configuration>

  <configSections>

    <section name="validation" type="Microsoft.Practices.EnterpriseLibrary.Validation.Configuration.ValidationSettings, Microsoft.Practices.EnterpriseLibrary.Validation, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

    <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

  </configSections>

  <validation>

    <type defaultRuleset="Rule Set" assemblyName="Commons, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"

      name="Commons.Customers">

      <ruleset name="Rule Set">

        <properties>

          <property name="Age">

            <validator lowerBound="18" lowerBoundType="Inclusive" upperBound="50"

              upperBoundType="Inclusive" negated="false" messageTemplate="本网站只能18-50岁的人才能注册"

              messageTemplateResourceName="" messageTemplateResourceType=""

              tag="" type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.RangeValidator, Microsoft.Practices.EnterpriseLibrary.Validation, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"

              name="old" />

          </property>

          <property name="Email">

            <validator pattern="/w+([-+.']/w+)*@/w+([-.]/w+)*/./w+([-.]/w+)*"

              options="IgnoreCase" patternResourceName="" patternResourceType=""

              messageTemplate="E-mail地址格式不能正确" messageTemplateResourceName=""

              messageTemplateResourceType="" tag="" type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.RegexValidator, Microsoft.Practices.EnterpriseLibrary.Validation, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"

              name="Regex Validator" />

          </property>

          <property name="UserName">

            <validator lowerBound="5" lowerBoundType="Inclusive" upperBound="10"

              upperBoundType="Inclusive" negated="false" messageTemplate="用户名必须在5-10字符"

              messageTemplateResourceName="" messageTemplateResourceType=""

              tag="" type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.StringLengthValidator, Microsoft.Practices.EnterpriseLibrary.Validation, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"

              name="length" />

            <validator negated="false" messageTemplate="用户名不能为空" messageTemplateResourceName=""

              messageTemplateResourceType="" tag="" type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.NotNullValidator, Microsoft.Practices.EnterpriseLibrary.Validation, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"

              name="Not Null Validator" />

          </property>

        </properties>

      </ruleset>

    </type>

  </validation>

  <appSettings />

  <system.web>

    <!--

            设置 compilation debug="true" 将调试符号插入

            已编译的页面中。但由于这会

            影响性能,因此只在开发过程中将此值

            设置为 true

        -->

    <compilation debug="false" />

    <!--

            通过 <authentication> 节可以配置 ASP.NET 使用的

            安全身份验证模式,

            以标识传入的用户。

        -->

    <authentication mode="Windows" />

    <!--

            如果在执行请求的过程中出现未处理的错误,

            则通过 <customErrors> 节可以配置相应的处理步骤。具体说来,

            开发人员通过该节可以配置

            要显示的 html 错误页

            以代替错误堆栈跟踪。

 

        <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">

            <error statusCode="403" redirect="NoAccess.htm" />

            <error statusCode="404" redirect="FileNotFound.htm" />

        </customErrors>

        -->

  </system.web>

</configuration>

 

 

下面就是进行验证的代码了

Customers customer = new Customers();

        customer.UserName = TextBox1.Text;

        customer.Email = TextBox3.Text;

        customer.Age = int.Parse(TextBox2.Text);

        ValidationResults results = Validation.ValidateFromConfiguration<Customers>(customer);

        StringBuilder sb = new StringBuilder();

        foreach (ValidationResult result in results)

        {

 

            sb.Append(string.Format("字段:{0}-出错信息:{1}", result.Key.ToString(), result.Message.ToString()) + "<br/>");

 

        }

        Label1.Text = sb.ToString();

 

 

由于Terylee博客上的代码基于2007-1版本的,我的基于4月的版本,里面有所区别的,大概有2处不同之处,时间关系没有标出来的,请谅解!

支持我,支持我的博客,但是更要支持TerryLee,尤其要支持盖茨的Microsoft

 
原创粉丝点击