How to validate a property (via IncludeProperties) within a specific ruleset (via IncludeRuleSets) with FluentValidation?

After several days of pain and tears I found a very bad looking solution but, nevertheless, working.

var validator = new WeirdValidator();

var ruleDescriptor = validator.CreateDescriptor();
var rulesOfMember = ruleDescriptor.GetRulesForMember(nameof(instanceToValidate.AgeMin));                
var exactRule = rulesOfMember.FirstOrDefault(c => c.RuleSets.Contains(WeirdValidator.CustomRuleSet));

var errorList = exactRule.Validate(
   new ValidationContext<TestClass>(instanceToValidate, new PropertyChain(),
   new RulesetValidatorSelector(WeirdValidator.CustomRuleSet)));

The main idea was to find the exact rule for exact property and to execute only one. It turned out that IValidationRule has own Validate/ValidateAsync methods.

If someone knows better/more elegant solution, you are welcome.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top