c# – 有条件地验证集合
作者:互联网
public class ProspectValidator : AbstractValidator<Prospect>
{
public ProspectValidator()
{
RuleFor(p => p.CompetitorProducts)
.NotNull()
.When(p => !p.ExistingCustomer);
RuleFor(p => p.CompetitorProducts.Count)
.GreaterThan(0)
.When(p => p.CompetitorProducts != null && !p.ExistingCustomer);
}
}
此验证器检查如果ExistingCustomer为false,则CompetitorProducts不为null且至少包含一个元素.
它可以工作但是可以把它写成一条规则吗?
解决方法:
在单个命令中有两个选项可以执行此操作,但它们都有点棘手,因为您需要验证内部属性,同时验证包含类不为null.它们都围绕Cascade
property旋转(参见“设置级联模式”)以停止第一个错误的验证.
首先,您可以使用Must进行验证.您将需要指定一个WithMessage,以避免获得通用“’竞争对手产品’未达到指定条件.”错误.您可能还希望覆盖WithErrorCode,因为它默认为Predicate.请注意,这仅显示在第二个验证错误上;第一个错误仍将正确返回该属性不能为null的消息.
RuleFor(p => p.CompetitorProducts)
.Cascade(CascadeMode.StopOnFirstFailure)
.NotNull()
.Must(p => p.Count > 0)
.WithMessage("{PropertyName} must be greater than '0'")
.When(p => !p.ExistingCustomer);
其次,您可以为CompetitorProducts类提供整体验证器.这将允许您使用FluentValidation管理错误消息和代码.如果您必须在类上进行其他验证,这将很有效,但如果您只需要验证单个属性,则可能过度.
public class ProspectValidator: AbstractValidator<Prospect>
{
public CurrentUserValidator()
{
RuleFor(p => p.CompetitorProducts)
.Cascade(CascadeMode.StopOnFirstFailure)
.NotNull()
.SetValidator(new CompetitorProductsValidator())
.When(p => !p.ExistingCustomer);
}
}
public class CompetitorProductsValidator : AbstractValidator<Prospect.CompetitorProducts>
{
public CompetitorProductsValidator()
{
RuleFor(p => p.Count)
.GreaterThan(0);
}
}
标签:c,fluentvalidation 来源: https://codeday.me/bug/20190624/1282005.html