gpt4 book ai didi

c# - 使用 FluentValidation 根据 bool 值的结果设置规则

转载 作者:太空宇宙 更新时间:2023-11-03 22:40:11 27 4
gpt4 key购买 nike

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

bool CorrespondanceAddressIsSecurityAddress
Address CorrespondanceAddress
Address SecurityAddress

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

用户的通信地址将始终填写,因此需要进行验证。用户可以选择他们的通信地址与他们的安全地址相同,当这种情况发生时,不需要验证安全地址,它可以留空。

我想做的是检查 CorrespondanceAddressIsSecurityAddress bool 值的状态,然后为安全地址设置一个验证器(如果它设置为 false),但我不确定语法需要执行此操作。

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

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

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

Cannot convert from '...FluentAddressValidator' to 'FluentValidation.Validators.IPropertyValidator

如何根据 bool 值设置规则?

最佳答案

The When and Unless methods can be used to specify conditions that control when the rule should execute. The Unless method is simply the opposite of 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
}
}

If you need to specify the same condition for multiple rules then you can call the top-level When method instead of chaining the When call at the end of the rule:

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

Link to documentation

关于c# - 使用 FluentValidation 根据 bool 值的结果设置规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52650318/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com