Quantcast
Channel: Fluent Validation for .NET
Viewing all articles
Browse latest Browse all 1917

New Post: Using SetCollectionValidator - Overriding/Adding RuleSet

$
0
0
Hi

The default behaviour is to cascade the ruleset selection to child validators. You can bypass this by writing your own implementation of IValidatorSelector rather than using the default RulesetValidatorSelector. Example:
public class MyValidatorSelector : IValidatorSelector {
    RulesetValidatorSelector _inner;
    string[] _ruleSetsToExecute;

    public MyValidatorSelector(string[] ruleSetsToExecute) {
        _inner = new RulesetValidatorSelector(ruleSetsToExecute);
        _ruleSetsToExecute = ruleSetsToExecute;
    }

    public bool CanExecute(IValidationRule rule, string propertyPath, ValidationContext context) {
        // If we're executing a child validator, and the child validator has no ruleset defined, then include it
        if (context.IsChildContext && string.IsNullOrEmpty(rule.RuleSet) && _ruleSetsToExecute.Length > 0) {
            return true;
        }
        return _inner.CanExecute(rule, propertyPath, context);
    }
}
Example usage:
public class MyValidator : AbstractValidator<Person> {
    public MyValidator() {
        RuleSet("test", () => {
            RuleFor(x => x.Surname).NotNull();
            RuleFor(x => x.Orders).SetValidator(new OrderValidator());
        });

        RuleFor(x => x.Forename).NotNull();
    }
}

public class OrderValidator : AbstractValidator<Order> {
    public OrderValidator() {
        RuleFor(x => x.ProductName).NotNull();
    }
}

var person = new Person() {
    Orders = {new Order()}
};

var validator = new MyValidator();

var rulesets = new[] { "test" };
var result = validator.Validate(person, selector: new MyValidatorSelector(rulesets));

Viewing all articles
Browse latest Browse all 1917

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>