Skip to content

ChildRules will corrupt the RuleSets of a validator passed to the SetValidator #1981

@sumtec

Description

@sumtec

FluentValidation version

Any older than 9.4

ASP.NET version

No response

Summary

The ChildRules will use a RuleSetValidatorSelector with a rule set "*". This will overwrite rule sets to be validated specified in the validation context. This will make the child validator malfunctioned.

Steps to Reproduce

		[Fact]
		public void ChildRules_works_with_SetValidator_and_RuleSet() {
			var validator = new RulesetChildValidatorRulesValidator();

			// If the validator inside a child rule specifies a rule set "b",
			// the rules inside the rule set "b" should not be used for the validation
			// if the validation context specified the ruleset "a"
			var result = validator.Validate(new Person {
				Orders = new List<Order> {
					new Order()
				}
			}, options => options.IncludeRuleSets("a"));

			result.Errors.Count.ShouldEqual(1);
			result.Errors[0].PropertyName.ShouldEqual("Surname");			

			// They shouldn't be executed if a different ruleset is chosen.
			result = validator.Validate(new Person {
				Orders = new List<Order> {
					new Order()
				}
			}, options => options.IncludeRuleSets("other"));

			result.Errors.Count.ShouldEqual(0);
		}

		private class RulesetChildValidatorRulesValidator : AbstractValidator<Person> {
			public RulesetChildValidatorRulesValidator() {
				RuleSet("a, b", () => {
					RuleFor(x => x.Surname).NotEmpty();
					RuleFor(x => x).ChildRules(child => {
						child.RuleForEach(o => o.Orders).SetValidator(new RulesetOrderValidator());
					});
				});
			}

			private class RulesetOrderValidator : AbstractValidator<Order> {
				public RulesetOrderValidator() {
					RuleSet("b", () => {
						RuleFor(o => o.ProductName).NotEmpty();
					});
				}
			}
		}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions