FluentValidation: ValidationFailure should be aware of it's RuleSet

Is your feature request related to a problem? Please describe. When a ValidationFailure is constructed, it should be aware of the RuleSet name that it came from.

Describe the solution you’d like Please add the following to ValidationFailure

public string RuleSet { get; }

Describe alternatives you’ve considered I’ve attempted to foreach all of my rulesets, but unfortunately I don’t even see the validation failure when I do this.

var failures = new Dictionary<string, ValidationResult>();

foreach (var ruleSet in _ruleSets)
{
    var result = await _validator.ValidateAsync(self, opts => opts.IncludeRuleSets(ruleSet));
    failures[ruleSet] = result; // unfortunately this is always IsValid = true;
    isValid = isValid && result.Errors.All(x => x.Severity != Severity.Error);
}

Additional context Effectively I need to emit out validation failures based on the grouping of validation. In other words, a particular segment of my overall object can be valid or invalid based on a RuleSet.

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Comments: 18 (8 by maintainers)

Most upvoted comments

@ChaseFlorell Yes that’s correct, custom state is always per-validator, it’s not shared between the whole rule chain. However you can add an extension method that would apply it the whole chain quite easily:

public static IRuleBuilderOptions<T, TProperty> RuleState<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Func<T, object> stateProvider) {
	var wrapper = new Func<PropertyValidatorContext, object>(ctx => stateProvider((T) ctx.InstanceToValidate));
	return rule.Configure(config => {
		foreach (var validator in config.Validators) {
			validator.Options.CustomStateProvider = wrapper;
		}
	});
}

Then you can call:

RuleFor(x => x.Email).EmailAddress().NotNull().RuleState(_ => "Email");

It must be the last method in the chain, as it’ll only apply to any validators that precede it.

An individual rule can actually be part of multiple rulesets, so this will probably be an array of strings rather than a single string.

Thanks, that makes sense. Yes that seems like a good solution, I’ll get this added for a future version.

@ChaseFlorell Yeah, see Jeremy’s reply above. My point was if somehow CustomState was getting wiped out from one validation to the next, then that’s a problem (but it’s not). It’s easy to DRY up WithState via custom extension method.