lekso lekso - 3 months ago 35
C# Question

Can FluentValidation work with nested collections?

Can FluentValidation work with hierarchical collections? Can the following object with arbitrary number of Child nodes be validated?

public class Node
{
public string Id { get; set; }
public List<Node> ChildNodes { get; set; }
}


In very simple terms I'd like the following code to work:

public class NodeValidator : AbstractValidator<Node>
{
public NodeValidator()
{
RuleFor(x => x.ChildNodes).SetCollectionValidator(new NodeValidator());
RuleFor(x => x.Id).NotEmpty();
}
}


This line causes StackOverflow exception:

RuleFor(x => x.ChildNodes).SetCollectionValidator(new NodeValidator());


How can I validate property "Id" of a deeply nested object?

Answer

To avoid recursion in your ctor, I would correct your validator with

RuleFor(x => x.ChildNodes).SetCollectionValidator(this);

I gave it a try, and it seems to retrieve the validation errors correctly, but... I let you see if that's really what you need.

Comments