我正在使用 Fluent Validation 进行服务器端验证。我已经创建了一组将被验证的规则。所有这些规则都是我的验证器中的独立功能。
public SampleValidator()
{
Validate_Authorisation();
ValidateTitle_NotEmpty();
ValidateGender_NotEmpty();
ValidateFirstName_Regex();
ValidateFirstName_NotEmpty();
ValidateSurname_NotEmpty();
ValidateSurname_Regex();
ValidateMobilePhone_Regex();
}
private void Validate_Authorisation()
{
RuleFor(Model=> Model)
.Must(Model=> IsUserAuthorised(UserName))
.WithName("Authorisation Check");
}
private void ValidateTitle_NotEmpty()
{
RuleFor(model=> model)
.Must(title=> !string.IsNullOrEmpty(title))
.WithName("Title");
}
private void ValidateGender_NotEmpty()
{
RuleFor(model=> model)
.Must(Gender=> !string.IsNullOrEmpty(Gender))
.WithName("Gender");
}.... And others
现在,我想在我的授权验证失败时停止验证所有其他验证。我不想使用 CascadeMode.StopOnFirstFailure 因为它总是检查第一次验证失败并停止验证其他人。当授权验证失败时,有没有一种方法可以返回服务(从调用验证器的地方)。
最佳答案
如果您将 Validate_Authorisation
方法更改为以下内容:
private IRuleBuilderOptions<Model, string> Validate_Authorisation()
{
RuleFor(Model=> Model)
.Must(Model=> IsUserAuthorised(UserName))
.WithName("Authorisation Check");
}
然后您可以使用 dependentRules
扩展方法执行以下操作:
Validate_Authorisation().DependentRules(rules =>
{
ValidateTitle_NotEmpty();
ValidateGender_NotEmpty();
ValidateFirstName_Regex();
ValidateFirstName_NotEmpty();
ValidateSurname_NotEmpty();
ValidateSurname_Regex();
ValidateMobilePhone_Regex();
});
关于c# - Fluent Validation - 当特定验证失败时停止验证所有其他验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30928287/