C# 有条件地验证集合 公共类验证程序:AbstractValidator { 公共验证程序() { 规则(p=>p.CompetitorProducts) .NotNull() .When(p=>!p.ExistingCustomer); 规则(p=>p.CompetitorProducts.Count) .大于(0) .When(p=>p.CompetitorProducts!=null&&!p.ExistingCustomer); } }
此验证器检查如果C# 有条件地验证集合 公共类验证程序:AbstractValidator { 公共验证程序() { 规则(p=>p.CompetitorProducts) .NotNull() .When(p=>!p.ExistingCustomer); 规则(p=>p.CompetitorProducts.Count) .大于(0) .When(p=>p.CompetitorProducts!=null&&!p.ExistingCustomer); } },c#,fluentvalidation,C#,Fluentvalidation,此验证器检查如果ExistingCustomer为false,则CompetitorProducts不为null且至少有一个元素 它可以工作,但是否可以将其作为一条规则编写?在一个命令中有两个选项可以执行此操作,但这两个选项都有点棘手,因为您需要在验证包含的类是否为null的同时验证内部属性。它们都围绕(请参见“设置级联模式”)停止第一个错误的验证 首先,您可以使用Must进行验证。您需要使用message指定一个,,就像我所做的那样,以避免出现一个通用的“指定的条件不符合‘竞争对手产品’”错误
ExistingCustomer
为false,则CompetitorProducts
不为null且至少有一个元素
它可以工作,但是否可以将其作为一条规则编写?在一个命令中有两个选项可以执行此操作,但这两个选项都有点棘手,因为您需要在验证包含的类是否为null的同时验证内部属性。它们都围绕(请参见“设置级联模式”)停止第一个错误的验证 首先,您可以使用
Must
进行验证。您需要使用message指定一个,
,就像我所做的那样,以避免出现一个通用的“指定的条件不符合‘竞争对手产品’”错误。您可能还希望覆盖谓词
,因为它默认为谓词
。请注意,这将仅在第二次验证错误时显示;第一个错误仍然会正确返回属性不能为null的消息
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);
}
}
其次,您可以为CompetitorProducts
类作为一个整体提供验证器。这将允许您让FluentValidation管理错误消息和代码。如果必须在类上进行其他验证,那么这将很好地工作,但是如果只需要验证单个属性,那么这可能会有些过分
RuleFor(p => p.CompetitorProducts)
.Cascade(CascadeMode.StopOnFirstFailure)
.NotNull()
.Must(p => p.Count > 0)
.WithMessage("{PropertyName} must be greater than '0'")
.When(p => !p.ExistingCustomer);
公共类验证程序:AbstractValidator
{
公共CurrentUserValidator()
{
规则(p=>p.CompetitorProducts)
.Cascade(CascadeMode.StopOnFirstFailure)
.NotNull()
.SetValidator(新竞争对手产品验证器())
.When(p=>!p.ExistingCustomer);
}
}
公共类CompetitorProductsValidator:AbstractValidator
{
公共竞争产品验证人()
{
规则(p=>p.Count)
.大于(0);
}
}
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);
}
}