FluentValidation - Validating a View Model that contains a list of an Object
RuleForEach(
itemToValidate =>
new YourObjectValidator());
public class YourObjectValidator : AbstractValidator<YourObject>
{
public EdgeAPIAddressValidator()
{
RuleFor(r => r.YourProperty)
.MaximumLenght(100);
}
}
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();
}
}
This code deprecated: RuleFor(x => x.Guitars).SetCollectionValidator(new GuitarValidator());
This is new:
RuleForEach(x => x.Guitars).SetValidator(new GuitarValidator());