我可以向对象添加多个验证器吗?例如:
public interface IFoo { int Id { get; set; } string Name { get; set; } } public interface IBar { string Stuff { get; set; } } public class FooValidator : AbstractValidator<IFoo> { public FooValidator () { RuleFor(x => x.Id).NotEmpty().GreaterThan(0); } } public class BarValidator : AbstractValidator<IBar> { public BarValidator() { RuleFor(x => x.Stuff).Length(5,30); } } public class FooBar : IFoo,IBar { public int Id { get; set; } public string Name { get; set; } public string Stuff { get; set; } } public class FooBarValidator : AbstractValidator<FooBar> { public FooBarValidator() { RuleFor(x => x) .SetValidator(new FooValidator()) .SetValidator(new BarValidator()); } }
运行测试
FooBarValidator validator = new FooBarValidator(); validator.ShouldHaveValidationErrorFor(x => x.Id,0);
我得到一个InvalidOperationException:
Property name could not be automatically determined for expression x => x. Please specify either a custom property name by calling ‘WithName’.
有没有办法实现这个,或者我试图使用FluentValidation的方式,它不意味着被使用?
解决方法
RuleFor正在尝试创建一个属性级别的规则.您还可以使用AddRule函数添加通用规则.
使用这个,我创建了一个复合规则证明的概念.它需要一组其他验证器并运行它们.收益率代码来自FluentValidator的DelegateValidator.我不知道该怎么做,所以我从源头上抓住了这一点.我没有追踪它的全部目的,但一切似乎都是按照原样工作的:)
码
public interface IFoo { int Id { get; set; } string Name { get; set; } } public interface IBar { string Stuff { get; set; } } public class FooValidator : AbstractValidator<IFoo> { public FooValidator() { RuleFor(x => x.Id).NotEmpty().GreaterThan(0); } } public class BarValidator : AbstractValidator<IBar> { public BarValidator() { RuleFor(x => x.Stuff).Length(5,IBar { public int Id { get; set; } public string Name { get; set; } public string Stuff { get; set; } } public class CompositeValidatorRule : IValidationRule { private IValidator[] _validators; public CompositeValidatorRule(params IValidator[] validators) { _validators = validators; } #region IValidationRule Members public string RuleSet { get; set; } public IEnumerable<ServiceStack.FluentValidation.Results.ValidationFailure> Validate(ValidationContext context) { var ret = new List<ServiceStack.FluentValidation.Results.ValidationFailure>(); foreach(var v in _validators) { ret.AddRange(v.Validate(context).Errors); } return ret; } public IEnumerable<ServiceStack.FluentValidation.Validators.IPropertyValidator> Validators { get { yield break; } } #endregion } public class FooBarValidator : AbstractValidator<FooBar> { public FooBarValidator() { AddRule(new CompositeValidatorRule(new FooValidator(),new BarValidator())); } }
基础测试用例:
[TestMethod] public void TestValidator() { FooBarValidator validator = new FooBarValidator(); var result = validator.Validate(new FooBar()); }
我希望这有帮助.