基于.NET的FluentValidation数据验证实现(4)

public static class MyCustomValidators { public static IRuleBuilderOptions<T, IList<TElement>> ListMustContainFewerThan<T, TElement>(this IRuleBuilder<T, IList<TElement>> ruleBuilder, int num) { return ruleBuilder.Must(list => list.Count < num).WithMessage("The list contains too many items"); } }

在这里,我们在上创建一个扩展方法IRuleBuilder<T,TProperty>,并使用通用类型约束来确保此方法仅出现在对列表类型的智能感知中。在方法内部,我们以与以前相同的方式调用Must方法,但是这次我们在传入的RuleBuilder实例上调用它。我们还将要比较的项目数作为参数传递。现在,我们的规则定义可以重写为使用以下方法:

RuleFor(x => x.Pets).ListMustContainFewerThan(10);

我们还可以通过Custom方法来自定义验证器,它相比于Must的好处是允许针对同一规则返回多个错误(通过context.AddFailure多次调用该方法)。

public class PersonValidator : AbstractValidator<Person> { public PersonValidator() { RuleFor(x => x.Pets).Custom((list, context) => { if(list.Count > 10) { context.AddFailure("The list must contain 10 items or fewer"); } }); } }

到此这篇关于基于.NET的FluentValidation数据验证实现的文章就介绍到这了,更多相关.NET FluentValidation数据验证内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/d39ab55b6f956129eebb4104b5059fb9.html