企業(yè)庫提供了一個很強大的驗證應用程序模塊,特點是:
使用企業(yè)庫驗證應用程序模塊的優(yōu)勢:
企業(yè)庫驗證應用程序模塊提供了下列幾種驗證方法:
企業(yè)庫驗證應用程序模塊有2種使用模式:
本文講的是代碼模式,配置文件模式在高級篇再介紹 下面介紹如何使用Microsoft Enterprise Library 5.0中的驗證應用程序模塊的代碼模式.
添加引用: usingMicrosoft.Practices.EnterpriseLibrary.Validation.Validators; usingMicrosoft.Practices.EnterpriseLibrary.Validation; usingSystem.Collections.Generic; 2. 測試: 代碼
using System; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; using Microsoft.Practices.EnterpriseLibrary.Validation; using System.Collections.Generic; namespace test { class Program { staticint index =1; staticvoid Main(string[] args) { //驗證Customer類 Validator<Customer> customerValidator = ValidationFactory.CreateValidator<Customer>(); //設置Customer的CustomerName字段為null Customer myCustomer =new Customer(null); ValidationResults vr = customerValidator.Validate(myCustomer); Scan(vr); //設置Customer的CustomerName myCustomer.CustomerName ="HuangCong"; vr = customerValidator.Validate(myCustomer); Scan(vr); //創(chuàng)建一個日期 DateTime dt =new DateTime(1988, 01, 01); //創(chuàng)建一個日期驗證器 Validator<DateTime> v1 =new DateTimeRangeValidator(DateTime.Parse("2009-01-01"), DateTime.Parse("2010-01-01")); vr = v1.Validate(dt); Scan(vr); dt =new DateTime(2009, 5, 5); vr = v1.Validate(dt); Scan(vr); /* 其他的驗證類還有如下這些,大家可以自己實驗: And Composite Validator Contains Characters Validator Date Time Range Validator Domain Validator Enum Conversion Validator Not Null Validator Object Collection Validator Object Validator Or Composite Validator Property Comparison Validator Range Validator Regular Expression Validator Relative Date Time Validator String Length Validator Type Conversion Validator Single Member Validators 參考網(wǎng)站:http://msdn.microsoft.com/en-us/library/ff664694%28v=PandP.50%29.aspx */ } publicclass Customer { //Not Null Validator 驗證器,驗證該屬性不能為空值 [NotNullValidator] publicstring CustomerName; public Customer(string customerName) { this.CustomerName = customerName; } } privatestaticvoid Scan(ValidationResults vr) { Console.WriteLine("測試{0}:", index++); if (!vr.IsValid) { Console.WriteLine("出錯"); } else { Console.WriteLine("正確"); } Console.WriteLine("---------------------------------------"); } } } 3. 運行結(jié)果:
|
|