Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use fluent validation to validate an object which contains more objects of the same type?

I have a class Action which has a collection of more Action objects. Something like this:

public class Action
{
    ICollection<Action> SubActions;
}

This basically forms a tree structure (I make sure there are no cycles). I used Fluent Validation to write a validator for this class. Here is my Validator attempt:

public class ActionValidator : AbstractValidator<Action>
{
    public ActionValidator()
    {
        RuleFor(x => x.SubActions).SetCollectionValidator(new ActionValidator());
    }
}

Unity blows up when I try to resolve anything which depends on ActionValidator. More specifically, LINQPad crashes when it tries to resolve a service which depends on ActionValidator, presumably from a stack overflow.

There are other members in my Action class that I'm validating, but I've just put the important part for brevity. If I comment out the rule I've listed here, it works fine (except it's not validating subactions anymore).

I get the problem with my approach. I'm recursively constructing validators until something dies. But I'm just not sure how I'm to tell Fluent Validation to validate sub-objects this way.

like image 762
Ross Avatar asked Aug 18 '11 00:08

Ross


People also ask

How do you validate fluent validation?

To run the validator, instantiate the validator object and call the Validate method, passing in the object to validate. Customer customer = new Customer(); CustomerValidator validator = new CustomerValidator(); ValidationResult result = validator. Validate(customer);

How do you debug fluent validation rules?

There is no way to debug Fluent Validator code with Visual Studio tools. You need to comment the specific part of code (RuleFor) that you want to test. Keep doing it until all rules are tested.

What is fluent validation for?

Fluent Validation is a validation library for . NET, used for building strongly typed validation rules for business objects. Fluent validation is one way of setting up dedicated validator objects, that you would use when you want to treat validation logic as separate from business logic.

Is fluent validation client side?

FluentValidation is a server-side library and does not provide any client-side validation directly. However, it can provide metadata which can be applied to the generated HTML elements for use with a client-side framework such as jQuery Validate in the same way that ASP. NET's default validation attributes work.


1 Answers

Change the rule that validates the same type to:

Rulefor(x => x.SubActions).SetCollectionValidator(this);
like image 134
Ross Avatar answered Nov 02 '22 23:11

Ross