3

I am using FluentValidation.AspNetcore 8.2.2 and have a object model that contains a list of child items of the same type. I would like to use fluent validation to validate the object. When trying to set the validator for the child object I either run into a stack overflow exception and/or the collection has changed (typical foreach loop issue).

In order to test and find resolution I have setup a simple .net core class library project with a unit test.

Base Model

using FluentValidation;

public class BaseModelItem
    {
        public int ItemId { get; set; }

        public string Name { get; set; }

        private List<BaseModelItem> ChildItems { get; set; }
    }

 public class BaseModelItemValidator : AbstractValidator<BaseModelItem>
    {
        public BaseModelItemValidator()
        {
            RuleFor(i => i.ItemId).GreaterThanOrEqualTo(0).WithMessage("Item id may not be negative.");
            RuleFor(i => i.Name).NotNull().NotEmpty().WithMessage("Item name cannot be empty.");
            RuleFor(i => i.ChildItems).ForEach(i => i.SetValidator(new BaseModelItemValidator()));
        }

    }

unit test

 public class Tests
    {
       [Test]
        public void Test_Name_Cannot_Null()
        {
            var item = new BaseModelItem
            {
                ItemId = 2,
                Name = null,
                ChildItems = new List<BaseModelItem>()
            };
            var validator = new BaseModelItemValidator();
            validator.ShouldHaveValidationErrorFor(t => t.Name, item);
            Assert.Pass();
        }
}

This test will cause a stack overflow exception. I have tried using backing fields, initializing or even changing to an array. I can successfully negate the stackover flow exception by using a custom validator.

 public class BaseModelItemValidator : AbstractValidator<BaseModelItem>
    {
        public BaseModelItemValidator()
        {
            RuleFor(i => i.ItemId).GreaterThanOrEqualTo(0).WithMessage("Item id may not be negative.");
            RuleFor(i => i.Name).NotNull().NotEmpty().WithMessage("Item name cannot be empty.");
            RuleFor(i => i.ChildItems).Must(BeValidChildItemList);
        }
        private bool BeValidChildItemList(List<BaseModelItem> list)
        {
            if (list.Count > 0)
            {
                RuleFor(i => i.ChildItems).ForEach(i => i.SetValidator(new BaseModelItemValidator()));

            }
            return true;
        }
    }

Allows it to validate objects without child items. However if you run a test with populated child objects I get the error "Collection was modified; enumeration operation may not execute". Stack trace

StackTrace:
   at System.ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion()
   at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
   at System.Linq.Enumerable.SelectManySingleSelectorIterator`2.MoveNext()
   at System.Linq.Enumerable.WhereEnumerableIterator`1.MoveNext()
   at FluentValidation.AbstractValidator`1.Validate(ValidationContext`1 context) in ****\FluentValidation\src\FluentValidation\AbstractValidator.cs:line 115
   at FluentValidation.DefaultValidatorExtensions.Validate[T](IValidator`1 validator, T instance, IValidatorSelector selector, String ruleSet) in ******\FluentValidation\src\FluentValidation\DefaultValidatorExtensions.cs:line 876
   at FluentValidation.TestHelper.ValidationTestExtension.TestValidate[T,TValue](IValidator`1 validator, Expression`1 expression, T instanceToValidate, TValue value, String ruleSet, Boolean setProperty) in ******\FluentValidation\src\FluentValidation\TestHelper\ValidatorTestExtensions.cs:line 101
   at FluentValidation.TestHelper.ValidationTestExtension.ShouldHaveValidationErrorFor[T,TValue](IValidator`1 validator, Expression`1 expression, T objectToTest, String ruleSet) in *******\FluentValidation\src\FluentValidation\TestHelper\ValidatorTestExtensions.cs:line 40
   at Tests.Tests.Test_Name_Cannot_Null_Nested() in \FluentValidationChildern\FluentValidationChildern.Tests\UnitTest1.cs:line 55

I am unable to find a feasible resolution.

0

4 Answers 4

2

Although I have been unable to get Fluent to work using the SetValidator method, I do have a workaround which is working and can be improved on.

on the child list I set use the 'Must' method and then implement a manual function to loop the child items and construct the validator object manually and check the result.

 public class BaseModelItemValidator : AbstractValidator<BaseModelItem>
    {
        public BaseModelItemValidator()
        {
            RuleFor(i => i.ItemId).GreaterThanOrEqualTo(0).WithMessage("Item id may not be negative.");
            RuleFor(i => i.Name).NotNull().NotEmpty().WithMessage("Item name cannot be empty.");
            RuleFor(i => i.ChildItems).Must(BeValidChildItemList);
        }
        private bool BeValidChildItemList(List<BaseModelItem> list)
        {
            if (list == null || list.Count == 0) return true;
            foreach (var child in list)
            {
                var validator = new BaseModelItemValidator();
                var validatorResults = validator.Validate(child);
                if (!validatorResults.IsValid)
                {
                    return false;
                }
            }
            return true;
        }
    }
1

It would seem the solution is to use the same instance of the validator like this:

public class BaseModelItemValidator : AbstractValidator<BaseModelItem>
{
    public BaseModelItemValidator()
    {
        RuleFor(i => i.ItemId).GreaterThanOrEqualTo(0).WithMessage("Item id may not be negative.");
        RuleFor(i => i.Name).NotNull().NotEmpty().WithMessage("Item name cannot be empty.");
        RuleFor(i => i.ChildItems).ForEach(i => i.SetValidator(this));
    }

}

I can confirm this is working for me. Credit to this issue

2
  • Thanks, this worked for me. Do you maybe know if there is any chance of recursive deadlock or other issues using it like this? (For example I have a class named A: object of class A contains List<A>()) Jun 21, 2023 at 9:27
  • 1
    I've been running this solution for a while without any issues. Not sure if that helps you? Jun 28, 2023 at 21:53
0

I had a similar requirement where in I had to validate a object which had a list of objects of same type as children. What I did was I overrode the Validate method of my validator and added logic something like

public override ValidationResult Validate(ValidationContext<BaseModelItem> context)
{
    var result = base.Validate(context);
    var obj = context.InstanceToValidate;

    if (obj.ChildItems != null && obj.ChildItems.Count > 0)
    {
        foreach (var item in obj.ChildItems)
        {
            var childResult = base.Validate(item);
            foreach (var error in childResult.Errors)
            {
                result.Errors.Add(error);
            }
        }
    }

    return result;
}

I would have loved to use the SetValidator somehow but couldn't find a way to do it. But anyways, this override returns ValidationResult object that I expect

0

I've tried these solutions, but non of them produced a proper validation error message!

I came up with this to solve this issue.

public override ValidationResult Validate(ValidationContext<BaseModelItem> context)
{
    var result = base.Validate(context);
    var obj = context.InstanceToValidate;

    if (obj.ChildItems != null && obj.ChildItems.Count > 0)
    {
        var cnt = 0;
        foreach (var item in obj.ChildItems)
        {
            var childContext = context.CloneForChildValidator(item);
            childContext.PropertyChain.Add(nameof(BaseModelItem.ChildItems));
            childContext.PropertyChain.AddIndexer(cnt);
            var childResult = Validate(childContext);

            cnt++;
        }
    }

    return result;
}
1
  • Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it’d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren’t as familiar with the syntax or struggling to understand the concepts. Would you kindly edit your answer to include additional details for the benefit of the community? Jun 16, 2023 at 1:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.