Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FluentValidation - Validating a View Model that contains a list of an Object

This code deprecated: RuleFor(x => x.Guitars).SetCollectionValidator(new GuitarValidator());

This is new:

RuleForEach(x => x.Guitars).SetValidator(new GuitarValidator());

You would add this to your CustomerViewModelValidator

RuleFor(x => x.Guitars).SetCollectionValidator(new GuitarValidator());

So your CustomerViewModelValidator would look like this:

public class CustomerViewModelValidator : AbstractValidator<CustomerViewModel>
{
    public CustomerViewModelValidator()
    {
        RuleFor(x => x.FirstName).NotNull();
        RuleFor(x => x.LastName).NotNull();
        RuleFor(x => x.Phone).NotNull();
        RuleFor(x => x.EmailAddress).NotNull();
        RuleFor(x => x.Guitars).SetCollectionValidator(new GuitarValidator());
    }
}

Add the GuitarValidator would look something like:

public class GuitarValidator : AbstractValidator<Guitar>
{
    public GuitarValidator()
    {
        // All your other validation rules for Guitar. eg.
        RuleFor(x => x.Make).NotNull();
    }
 }

RuleForEach(
  itemToValidate => 
     new YourObjectValidator());


public class YourObjectValidator : AbstractValidator<YourObject>
{
  public EdgeAPIAddressValidator()
  {
     RuleFor(r => r.YourProperty)
         .MaximumLenght(100);
  }
}

It works with the latest version of Fluent and contains a complete example to be used.

The code in the answer it's deprecated.