我们有一个条件要求,即只有在打开标志时才应将空规则应用于字段。类似下面的代码。
这是正确的做法吗?
public AccountSetupModelValidator(ISessionProvider sessionProvider)
{
var regexPatterns = new RegExPatterns();
RuleFor(x => x.MemorableDate)
.NotEmpty().WithLocalizedMessage(ResourceAreas.Messages.Message_AccountSetup_1001_memorabledate);
RuleFor(x => x.MemorableDateAnswer)
.NotEmpty().WithLocalizedMessage(ResourceAreas.Messages.Message_AccountSetup_1001_memorabledateanswer)
.Matches(regexPatterns.MemorableDateFormat).WithLocalizedMessage(ResourceAreas.Messages.Message_Onboarding_100007_memorabledateinvalidformat)
.Length(5).WithLocalizedMessage(ResourceAreas.Messages.Message_Onboarding_100006_maxlength);
RuleFor(x => x.SecurityQuestion)
.NotEmpty().WithLocalizedMessage(ResourceAreas.Messages.Message_AccountSetup_1001_securityquestion);
RuleFor(x => x.SecurityAnswer)
.NotEmpty().WithLocalizedMessage(ResourceAreas.Messages.Message_AccountSetup_1001_securityanswer)
.Length(1, 40).WithLocalizedMessage(ResourceAreas.Messages.Message_Onboarding_100006_maxlength);
if (sessionProvider.OnboardingApplicationData.ToggleNavigationView.HasProvisionalAccount)
{
RuleFor(x => x.TempCardNumber)
.NotEmpty().WithLocalizedMessage(ResourceAreas.Messages.Message_AccountSetup_100006_tempcard)
.Matches(regexPatterns.NumericOnly)
.WithLocalizedMessage(ResourceAreas.Messages.Message_Onboarding_100007_numbersonly)
.Length(15).WithLocalizedMessage(ResourceAreas.Messages.Message_AccountSetup_100006_tempcard);
RuleFor(x => x.SecurityCode)
.NotEmpty().WithLocalizedMessage(ResourceAreas.Messages.Message_AccountSetup_100006_tempcard)
.Matches(regexPatterns.NumericOnly)
.WithLocalizedMessage(ResourceAreas.Messages.Message_Onboarding_100007_numbersonly)
.Length(4).WithLocalizedMessage(ResourceAreas.Messages.Message_AccountSetup_100006_securitycode);
}
}
答案 0 :(得分:7)
我建议不要尝试依赖你的sessionProvider,因为这会使得独立测试验证器变得更加困难。
相反,请使用FluentValidation's conditional When() and Unless()方法。
如果您的属性HasProvisionalAccount是(或可以放在)模型类,您可以重写这样的部分:
// remove the if() statement, and use .When()
RuleFor(x => x.TempCardNumber)
.NotEmpty().WithLocalizedMessage(ResourceAreas.Messages.Message_AccountSetup_100006_tempcard)
.Matches(regexPatterns.NumericOnly)
.WithLocalizedMessage(ResourceAreas.Messages.Message_Onboarding_100007_numbersonly)
.Length(15).WithLocalizedMessage(ResourceAreas.Messages.Message_AccountSetup_100006_tempcard)
.When(x => x.HasProvisionalAccount);
RuleFor(x => x.SecurityCode)
.NotEmpty().WithLocalizedMessage(ResourceAreas.Messages.Message_AccountSetup_100006_tempcard)
.Matches(regexPatterns.NumericOnly)
.WithLocalizedMessage(ResourceAreas.Messages.Message_Onboarding_100007_numbersonly)
.Length(4).WithLocalizedMessage(ResourceAreas.Messages.Message_AccountSetup_100006_securitycode)
.When(x => x.HasProvisionalAccount);
每个规则仅在HasProvisionalAccount为真时执行。