FluentValidation具体使用案例

可以使用NuGet 添加类库

 

下面是程序:

using FluentValidation; using System; using System.Linq;

namespace TestFluentValidation {  

class Program     {    

     static void Main(string[] args)        

{            

    var orders = new Orders() { DisCount = 2,

    CustomerID = "1",

    OrderDate = DateTime.Now.AddDays(-1).Date

};            

        IValidator validator = new OrdersValidator();    

        var results = validator.Validate(orders);

        var validationSucceeded = results.IsValid;    

        var failures = results.Errors;       

        Console.WriteLine(failures.Any(t => t.PropertyName == "CustomerID"));     

        Console.WriteLine(failures.Any(t => t.PropertyName == "DisCount"));     

        Console.WriteLine(failures.Any(t => t.PropertyName == "OrderDate.Date"));    

        failures.ToList().ForEach(t => Console.WriteLine(t.ErrorMessage));

        Console.Read();

        }    

}

    public class Orders     {    

        public int ID { get; set; }

        public string CustomerID { get; set; }

        public decimal DisCount { get; set; }

        public DateTime OrderDate { get; set; }

    }    

public class OrdersValidator : AbstractValidator<Orders>    

{        

public OrdersValidator()        

{            

            RuleFor(orders => orders.CustomerID).NotEmpty().Length(2, 20).WithName("CustomerID");

            RuleFor(orders => orders.DisCount).GreaterThanOrEqualTo(0).LessThan(1).WithMessage("discount must between 0 and 1!");

            RuleFor(orders => orders.OrderDate.Date).GreaterThanOrEqualTo(DateTime.Now.Date).WithName("Order Date");   

      }   

  }

}

posted @ 2017-04-27 19:25  龙骑科技  阅读(659)  评论(0编辑  收藏  举报