起因:
本人国庆无聊,不知道干嘛,
所以模仿FluentValidation写了个简化版的ObjectValidator
个人设想是能用类似fluent的方式创建验证规则,然后使用者缓存并验证自己的对象
现在第一次在博客园发了这篇文章,希望各位大神能在百忙之中抽空批评教育我,个人感激不尽
源代码:
代码放在了 https://github.com/fs7744/ObjectValidator
nuget:https://www.nuget.org/packages/ObjectValidator/
使用示例:
Container.Init(); // Only need init in your app once var builder = Validation.NewValidatorBuilder<Student>();
builder.RuleSet("A", b =>
{
b.RuleFor(i => i.Age)
.Must(i => i >= && i <= )
.OverrideName("student age")
.OverrideError("not student")
.ThenRuleFor(i => i.Name)
.Must(i => !string.IsNullOrWhiteSpace(i))
.OverrideName("student name")
.OverrideError("no name");
});
var v = builder.Build(); var student = new Student() { Age = , Name = "v" };
var context = Validation.CreateContext(student);
var result = v.Validate(context);
Assert.IsNotNull(result);
Assert.True(result.IsValid);
Assert.True(result.Failures.Count == ); student = new Student() { Age = , Name = string.Empty };
context = Validation.CreateContext(student);
result = v.Validate(context);
Assert.IsNotNull(result);
Assert.False(result.IsValid);
Assert.True(result.Failures.Count == );
Assert.AreEqual(, result.Failures[].Value);
Assert.AreEqual("student age", result.Failures[].Name);
Assert.AreEqual("not student", result.Failures[].Error);