.NET验证组件Fluent Validation使用指南

2019-05-23 05:58:53王旭

     string County { get; set; }
     string Postcode { get; set; }
     Country Country { get; set; }
 }
 public class Address : IAddress
 {
     public string Line1 { get; set; }
     public string Line2 { get; set; }
     public string Town { get; set; }
     public string County { get; set; }
     public string Postcode { get; set; }
     public Country Country { get; set; }
     public int Id { get; set; }
 }
 public class Country
 {
     public string Name { get; set; }
 }
 public interface IOrder
 {
     decimal Amount { get; }
 }
 public class Order : IOrder
 {
     public string ProductName { get; set; }
     public decimal Amount { get; set; }
 }

对Person的指定验证规则:  
 

 using FluentValidation;
 public class CustomerValidator: AbstractValidator<Customer>
 {
   public CustomerValidator()
   {
     RuleFor(customer => customer.Surname).NotEmpty();
     RuleFor(customer => customer.Forename).NotEmpty().WithMessage("Please specify a first name");
     RuleFor(customer => customer.Discount).NotEqual(0).When(customer => customer.HasDiscount);
     RuleFor(customer => customer.Address).Length(20, 250);
     RuleFor(customer => customer.Postcode).Must(BeAValidPostcode).WithMessage("Please specify a valid postcode");
   }
   private bool BeAValidPostcode(string postcode)
   {
     // custom postcode validating logic goes here
   }
 }
 // 手动验证规则
 Customer customer = new Customer();
 CustomerValidator validator = new CustomerValidator();
 ValidationResult results = validator.Validate(customer);
 bool validationSucceeded = results.IsValid;
 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注册验证规则。