C# 使用FluentValidation根据布尔值的结果设置规则
我有一个类C# 使用FluentValidation根据布尔值的结果设置规则,c#,fluentvalidation,C#,Fluentvalidation,我有一个类属性,它包含以下三个属性: bool CorrespondanceAddressIsSecurityAddress Address CorrespondanceAddress Address SecurityAddress address类只是一个基本的address类,它保存有关用户地址的详细信息 将始终填写用户的对应地址,因此需要进行验证。用户可以选择其对应地址与安全地址相同,当发生这种情况时,无需验证安全地址,并且可以将其保留为空 我想做的是检查correspondenceAd
属性
,它包含以下三个属性:
bool CorrespondanceAddressIsSecurityAddress
Address CorrespondanceAddress
Address SecurityAddress
address类只是一个基本的address类,它保存有关用户地址的详细信息
将始终填写用户的对应地址,因此需要进行验证。用户可以选择其对应地址与安全地址相同,当发生这种情况时,无需验证安全地址,并且可以将其保留为空
我想做的是检查correspondenceAddressisSecurityAddress
布尔值的状态,然后为安全地址设置一个验证器(如果设置为false),但我不确定执行此操作所需的语法
目前,控制属性类验证的类包含以下两行:
RuleFor(p => p.CorrespondanceAddressIsSecurityAddress)
.NotNull()
.WithMessage("CorrespondanceAddressIsSecurityAddress cannot be null");
RuleFor(p => P.CorrespondanceAddressIsSecurityAddress
.Equals(false))
.SetValidator(new FluentAddressValidator());
但是,设置验证器的第二条规则给出了一个语法错误,即
无法从“…FluentAddressValidator”转换为“FluentValidation.Validators.IPropertyValidator”
如何根据布尔值设置规则
When
和除非
方法可用于指定控制何时执行规则的条件。except
方法与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(x => !x.CorrespondanceAddressIsSecurityAddress, () =>
{
RuleFor(x => x.SecurityAddress)
.NotNull().WithMessage("Security address cannot be null")
.SetValidator(new AddressValidator());
// another RuleFor calls
});