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:
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));