这里要介绍一款与企业库VAB(Validation Application Block),ASP.NET MVC基于Attribute声明式验证所不同的验证组件,FluentValidation,其利用表达式语法链式编程,使得验证组件与实体分开。我喜欢他的原因是喜欢表达式,喜欢链式的感觉,大有一气呵成之意。
进入今天的主题首先如果你还没有这款组件,你可以利用VS2010的NuGet安装,(如果不会的请安装上篇开源DataBase组件:FluentMigrator中提到的方式安装),命令为:
498)this.width=498;'' onmousewheel = ''javascript:return big(this)'' style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="未命名" border="0" alt="未命名" src="/uploadfile/201301/5/13152234922.jpg" width="552" height="144" />
现在我们可以开始体验了,实体类do任然是上节的Orders:
do:
- 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");
- }
- }
看见这样的代码你的感觉如何?现在式的语言讲究的不仅在于功能,还有语义。
下面我们来写个简单的测试类测试它:
- [TestMethod]
- public void TestMethod1()
- {
- 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;
- Assert.IsTrue(failures.Any(t => t.PropertyName == "CustomerID"));
- Assert.IsTrue(failures.Any(t => t.PropertyName == "DisCount"));
- Assert.IsTrue(failures.Any(t => t.PropertyName == "OrderDate.Date"));
- failures.ToList().ForEach(t=>Debug.WriteLine(t.ErrorMessage));
- }
|
原