设为首页 - 加入收藏 ASP站长网(Aspzz.Cn)- 科技、建站、经验、云计算、5G、大数据,站长网!
热搜: 创业者 数据 手机
当前位置: 首页 > 站长学院 > Asp教程 > 正文

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

发布时间:2020-11-22 15:29 所属栏目:120 来源:网络整理
导读:public class PersonValidator : AbstractValidatorPerson { public PersonValidator() { RuleFor(x = x.Pets).Must(list = list.Count 10).WithMessage("The list must contain fewer than 10 items"); }} 为了使

public class PersonValidator : AbstractValidator<Person> { public PersonValidator() { RuleFor(x => x.Pets).Must(list => list.Count < 10) .WithMessage("The list must contain fewer than 10 items"); } }

为了使我们自己定义的验证器可以重用,我们可以将其包装为可作用于任何List<T>类型的扩展方法。

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数据验证内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

(编辑:ASP站长网)

网友评论
推荐文章
    热点阅读