望大神批评教育国庆无聊之作:ObjectValidator

起因:

本人国庆无聊,不知道干嘛,

所以模仿FluentValidation写了个简化版的ObjectValidator

个人设想是能用类似fluent的方式创建验证规则,然后使用者缓存并验证自己的对象

现在第一次在博客园发了这篇文章,希望各位大神能在百忙之中抽空批评教育我,个人感激不尽

源代码:

代码放在了 https://github.com/fs7744/ObjectValidator

nuget:https://www.nuget.org/packages/ObjectValidator/

使用示例:

 
 1 Container.Init(); // Only need init in your app once
 2 
 3 var builder = Validation.NewValidatorBuilder<Student>();
 4 builder.RuleSet("A", b =>
 5 {
 6     b.RuleFor(i => i.Age)
 7             .Must(i => i >= 0 && i <= 18)
 8             .OverrideName("student age")
 9             .OverrideError("not student")
10         .ThenRuleFor(i => i.Name)
11             .Must(i => !string.IsNullOrWhiteSpace(i))
12             .OverrideName("student name")
13             .OverrideError("no name");
14 });
15 var v = builder.Build();
16 
17 var student = new Student() { Age = 13, Name = "v" };
18 var context = Validation.CreateContext(student);
19 var result = v.Validate(context);
20 Assert.IsNotNull(result);
21 Assert.True(result.IsValid);
22 Assert.True(result.Failures.Count == 0);
23 
24 student = new Student() { Age = 23, Name = string.Empty };
25 context = Validation.CreateContext(student);
26 result = v.Validate(context);
27 Assert.IsNotNull(result);
28 Assert.False(result.IsValid);
29 Assert.True(result.Failures.Count == 1);
30 Assert.AreEqual(23, result.Failures[0].Value);
31 Assert.AreEqual("student age", result.Failures[0].Name);
32 Assert.AreEqual("not student", result.Failures[0].Error);

 

posted @ 2015-10-03 20:47  victor.x.qu  阅读(363)  评论(0编辑  收藏  举报