之前就有在 .net 时代介绍过了.
这个 dll 也支持 .net core 而且一直有人维护.
对比 data annotation 的 validation, 我越来越觉得这个 fluent 好用多了.
一堆 Attribute 在 property 上面真的很乱.
安装很容易
nuget : https://www.nuget.org/packages/FluentValidation.AspNetCore/
然后 startup.cs
services.AddMvc().AddFluentValidation(fvc => fvc.RegisterValidatorsFromAssemblyContaining<Startup>()).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
build in rule :
https://fluentvalidation.net/built-in-validators
complex 的做法 :
写一个 child validator, 然后 SetValidator. 一定要 set 哦, 不会自动的
RuleFor(o => o.Address).NotNull(); RuleFor(o => o.Address).SetValidator(new AddressValidator());
或者直接定义, 不过要记得另外处理 null 的情况哦
RuleFor(o => o.Address).NotNull(); RuleFor(o => o.Address.text1).NotEmpty().When(o => o.Address != null);