.NET業務實體類驗證組件Fluent Validation

來源:互聯網
上載者:User

標籤:http   io   ar   os   使用   sp   for   資料   on   

認識Fluent Vaidation.

  看到NopCommerce項目中用到這個組建是如此的簡單,將資料驗證從業務實體類中分離出來,真是一個天才的想法,後來才知道這個東西是一個開源的輕量級驗證組建。   Fluent Validation 翻譯為:流暢驗證   開源Codeplex其首頁簡介:該組件是一個輕量級的.NET類庫,使用流暢的介面定義和lambda運算式為構建一個業務類的驗證規則(A small validation library for .NET that uses a fluent interface and lambda expression for building validation rules for you business objects.)   這個類庫不僅僅可以使用的asp.net mvc項目中,普通的類庫中也可以使用,當然在asp.net form項目中也支援。 怎麼使用:    是不是好用,還要看使用時是否真的像其官網建議描述一樣。我比較喜歡其官網上的例子,一眼就能看出用法上的感覺,絕對是如其名,流暢,這個也一種解釋型語言常見的的一種用法,無限的對一個類型支援無限度個屬性擴充。      業務實體類: 複製代碼 1 public class Person  2 { 3     public string NameField; 4     public int Id { get; set; } 5     public string Surname { get; set; } 6     public string Forename { get; set; } 7  8     public List<Person> Children { get; set; } 9     public string[] NickNames { get; set; }10         11     public DateTime DateOfBirth { get; set; }12 13     public int? NullableInt { get; set; }14 15     public Person() 16     {17         Children = new List<Person>();18         Orders = new List<Order>();19     }20     21     public int CalculateSalary()22     {23         return 20;24     }25 26     public Address Address { get; set; }27     public IList<Order> Orders { get; set; }28 29     public string Email { get; set; }30     public decimal Discount { get; set; }31     public double Age { get; set; }32     public int AnotherInt { get; set; }33 34     public string CreditCard { get; set; }35 36     public int? OtherNullableInt { get; set; }37 }38 39 public interface IAddress 40 {41     string Line1 { get; set; }42     string Line2 { get; set; }43     string Town { get; set; }44     string County { get; set; }45     string Postcode { get; set; }46     Country Country { get; set; }47 }48 49 public class Address : IAddress 50 {51     public string Line1 { get; set; }52     public string Line2 { get; set; }53     public string Town { get; set; }54     public string County { get; set; }55     public string Postcode { get; set; }56     public Country Country { get; set; }57     public int Id { get; set; }58 }59 60 public class Country61 {62     public string Name { get; set; }63 }64 65 public interface IOrder 66 {67     decimal Amount { get; }68 }69 70 public class Order : IOrder 71 {72     public string ProductName { get; set; }73     public decimal Amount { get; set; }74 }複製代碼  對Person的指定驗證規則:   複製代碼 1 using FluentValidation; 2  3 public class CustomerValidator: AbstractValidator<Customer> 4 { 5   public CustomerValidator()  6   { 7     RuleFor(customer => customer.Surname).NotEmpty(); 8     RuleFor(customer => customer.Forename).NotEmpty().WithMessage("Please specify a first name"); 9     RuleFor(customer => customer.Discount).NotEqual(0).When(customer => customer.HasDiscount);10     RuleFor(customer => customer.Address).Length(20, 250);11     RuleFor(customer => customer.Postcode).Must(BeAValidPostcode).WithMessage("Please specify a valid postcode");12   }13 14   private bool BeAValidPostcode(string postcode) 15   {16     // custom postcode validating logic goes here17   }18 }19 20 // 手動驗證規則21 Customer customer = new Customer();22 CustomerValidator validator = new CustomerValidator();23 ValidationResult results = validator.Validate(customer);24 25 bool validationSucceeded = results.IsValid;26 IList<ValidationFailure> failures = results.Errors;複製代碼Flent validation怎麼與asp.net mvc驗證庫整合?  如果在asp.net mvc中現實中這麼用,可能會有很多人不會知道他,我們知道Asp.net MVC項目中有自己的驗證機構[企業庫VAB(Validation Application Block),基於Attribute聲明式驗證],其使用方法,也被我們都一直很認可,但其也有很多不夠靈活的,但Fluent Validation確實更靈活一點。使用起來多變性,流暢,而且驗證規則是一個單獨的類,是和業務實體物件分類的,我們不需要翔VAB一樣,需要在業務實體類上使用Attribute註冊驗證規則。   既然其不是ASP.NET MVC的預設驗證規則類庫,我們就需要註冊到ASP.NET MVC的驗證規則庫中。      複製代碼1 // 在Global.asax.cs中的Applicaton_Start()函數中註冊為asp.net mvc預設的驗證規則庫。2 3 // fluent validation4 FluentValidationModelValidatorProvider provider = new FluentValidationModelValidatorProvider(new AttributedValidatorFactory());5 ModelValidatorProviders.Providers.Add(provider);6 7 DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;複製代碼注意:  1,)作為Fluent Validation驗證規則類須繼承AbstractValidator<T>;   2,)我們也可以仿照NopCommerce的處理方法,對AttributeValidatorFactory類的Validator(Type type)函數重寫,在特殊的業務環境下支援其他驗證規則。

.NET業務實體類驗證組件Fluent Validation

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.