FluentValidation - checking a view model that contains a list of objects

I tried FluentValidation in a project that contains complex view models, and I read it here , but I don’t see how to set up rules to check the list of objects declared in my view model. In my example below, the list in the view model contains 1 or more guitar objects. Thanks

Show model

[FluentValidation.Attributes.Validator(typeof(CustomerViewModelValidator))] public class CustomerViewModel { [Display(Name = "First Name")] public string FirstName { get; set; } [Display(Name = "Last Name")] public string LastName { get; set; } [Display(Name = "Phone")] public string Phone { get; set; } [Display(Name = "Email")] public string EmailAddress { get; set; } public List<Guitar> Guitars { get; set; } } 

The guitar class used in the view model.

 public class Guitar { public string Make { get; set; } public string Model { get; set; } public int? ProductionYear { get; set; } } 

Show model validation class

  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(); //Expects an indexed list of Guitars here???? } } 
+20
c # asp.net-mvc-3 fluentvalidation
source share
5 answers

You would add this to your CustomerViewModelValidator

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

So your CustomerViewModelValidator will 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 GuitarValidator will look something like this:

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

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

This is new:

 RuleForEach(x => x.Guitars).SetValidator(new GuitarValidator()); 
+13
source share
 RuleForEach( itemToValidate => new YourObjectValidator()); public class YourObjectValidator : AbstractValidator<YourObject> { public EdgeAPIAddressValidator() { RuleFor(r => r.YourProperty) .MaximumLenght(100); } } 
0
source share

Works with the latest version of Fluent.

0
source share

It works with the latest version of Fluent and contains a complete example for use.

The code in the answer is out of date.

0
source share

All Articles