6

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?

2 Answers 2

8

The accepted answer is not actual anymore. SetCollectionValidator method is deprecated

Instead, you should use RuleForEach and SetValidator. The proper code is:

RuleForEach(x => x.ChildNodes).SetValidator(this);
Sign up to request clarification or add additional context in comments.

Comments

6

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

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.