2014-01-23 37 views
7

我在包含複雜視圖模型的項目上嘗試使用FluentValidation,並且讀取documentation here但我看不到如何設置規則以驗證列表在我的視圖模型中聲明的對象。在我下面的例子中,視圖模型中的列表包含1個或更多的吉他對象。在視圖模型使用的感謝FluentValidation - 驗證包含對象列表的視圖模型

視圖模型

[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; } 
    } 

吉他類

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

視圖模型驗證程序類

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???? 


     } 
    } 
+0

廣東話u必須爲separete驗證吉他課?你想在Ilist上做什麼樣的驗證,是否有多個元素? –

回答

19

你會添加到您的CustomerViewModelValidator

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

所以你CustomerViewModelValidator應該是這樣的:

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()); 
    } 
} 

添加GuitarValidator看起來是這樣的:

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