I'm using Fluent Validation for the server side validation. I've created a set of rules which will be validated. All these rules are individual functions in my validator.
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
Now, I want to stop validating all other validations when my Authorisation validation fails. I don't want to use CascadeMode.StopOnFirstFailure because it always checks for first validation failure and stop validating others. Is there a way I could return to the service (from where the validator is called) when the Authorisation validation fails.
If you change your
Validate_Authorisation
method to the following:You can then do the following using the
dependentRules
extension method: