使用FluentValidation

时间:2018-10-04 15:22:37

标签: c# fluentvalidation

我有一个类Property,其中包含以下三个属性:

bool CorrespondanceAddressIsSecurityAddress
Address CorrespondanceAddress
Address SecurityAddress

地址类只是一个基本的地址类,其中包含有关用户地址的详细信息。

用户的通讯地址将始终被填写,因此需要进行验证。用户可以选择将其通讯地址与他们的安全地址相同,如果发生这种情况,则无需验证安全地址,并且可以将其保留为空。

我想做的是检查CorrespondanceAddressIsSecurityAddress布尔值的状态,然后为安全地址设置一个验证器(如果将其设置为false),但是我不确定要使用哪种语法。做这个。

目前,控制属性类验证的类包含以下两行:

RuleFor(p => p.CorrespondanceAddressIsSecurityAddress)
   .NotNull()
   .WithMessage("CorrespondanceAddressIsSecurityAddress cannot be null");
RuleFor(p => P.CorrespondanceAddressIsSecurityAddress
   .Equals(false))
   .SetValidator(new FluentAddressValidator());

然而,设置验证器的第二条规则给出了语法错误,即

  

无法从'... FluentAddressValidator'转换为'FluentValidation.Validators.IPropertyValidator

如何根据布尔值设置规则?

1 个答案:

答案 0 :(得分:2)

  

WhenUnless方法可用于指定控制规则应在何时执行的条件。 Unless方法与When

相反

根据问题,您应该使用以下方式编写验证器:

public class PropertyValidator : AbstractValidator<Property>
{
    public PropertyValidator()
    {
        RuleFor(x => x.CorrespondanceAddress)
            .NotNull().WithMessage("Correspondence address cannot be null")
            .SetValidator(new AddressValidator());
        RuleFor(x => x.SecurityAddress)
            .NotNull().WithMessage("Security address cannot be null")
            .SetValidator(new AddressValidator())
            .When(x => !x.CorrespondanceAddressIsSecurityAddress); // applies to all validations chain
          //.Unless(x => x.CorrespondanceAddressIsSecurityAddress); - do the same as at previous line
    }
}
  

如果您需要为多个规则指定相同的条件,则可以调用顶级When方法,而不是在规则末尾链接When调用:

When(x => !x.CorrespondanceAddressIsSecurityAddress, () => 
{
    RuleFor(x => x.SecurityAddress)
       .NotNull().WithMessage("Security address cannot be null")
       .SetValidator(new AddressValidator());
    // another RuleFor calls
});

Link to documentation