Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 570
lekso Avatar asked Aug 15 '16 13:08

lekso


Video Answer


1 Answers

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.

like image 112
Raphaël Althaus Avatar answered Sep 17 '22 00:09

Raphaël Althaus