Fluent Validation - Stop validating all other validations when a specific validation fails

2.2k views Asked by At

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.

1

There are 1 answers

1
Yannick Meeus On

If you change your Validate_Authorisation method to the following:

private IRuleBuilderOptions<Model, string> Validate_Authorisation()
{
    RuleFor(Model=> Model)
        .Must(Model=> IsUserAuthorised(UserName))
        .WithName("Authorisation Check");
}

You can then do the following using the dependentRules extension method:

Validate_Authorisation().DependentRules(rules =>
{
    ValidateTitle_NotEmpty();
    ValidateGender_NotEmpty();
    ValidateFirstName_Regex();
    ValidateFirstName_NotEmpty();
    ValidateSurname_NotEmpty();
    ValidateSurname_Regex();
    ValidateMobilePhone_Regex(); 
});