Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FluentValidation: validate only the property that has changed

I want to only validate the property that has changed on my model, unfortunately fluent validation by default appears to validate every property that has a rule when calling Validator.Validate(instanceToValidate)

I've tried setting the PropertyChain to only include the property I want to validate and construct a new ValidationContext - It still validates all the rules.

Is there a way to achieve this using fluent validation?

Thanks

like image 407
antinutrino Avatar asked Oct 27 '25 14:10

antinutrino


1 Answers

so the fix is quite simple

var rule = _validator.CreateDescriptor();
var rules = rule.GetRulesForMember(e.PropertyName);
_validationResult = new ValidationResult(rules.SelectMany(x => x.Validate(new ValidationContext(_target))).ToList());

Find the rule(s) for the property that has changed and validate the target object against that ruleset.

like image 185
antinutrino Avatar answered Oct 30 '25 03:10

antinutrino



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!