如何使用Fluentvalidation对列表中的每个字符串进行validation?

我有一个MVC3视图模型定义为:

[Validator(typeof(AccountsValidator))] public class AccountViewModel { public List Accounts { get; set; } } 

使用FluentValidation(v3.3.1.0)定义validation为:

 public class AccountsValidator : AbstractValidator { public AccountsValidator() { RuleFor(x => x.Accounts).SetCollectionValidator(new AccountValidator()); //This won't work } } 

并且可能会定义帐户validation:

 public class AccountValidator : AbstractValidator { public OrderValidator() { RuleFor(x => x).NotNull(); //any other validation here } } 

我希望列表中的每个帐户都按照文档中的描述进行修改。 但是,对SetCollectionValidator的调用不起作用,因为在使用List时这不是一个选项,尽管如果它被定义为List ,那么该选项就在那里。 我错过了什么吗? 我可以更改我的模型以使用List然后定义Account类,但我真的不想更改我的模型以适应validation。

作为参考,这是我正在使用的视图:

 @model MvcApplication9.Models.AccountViewModel @using (Html.BeginForm()) { @*The first account number is a required field.*@ 
  • Account number* @Html.EditorFor(m => m.Accounts[0].Account) @Html.ValidationMessageFor(m => m.Accounts[0].Account)
  • for (int i = 1; i < Model.Accounts.Count; i++) {
  • Account number @Html.EditorFor(m => m.Accounts[i].Account) @Html.ValidationMessageFor(m => m.Accounts[i].Account)
  • } }

    以下应该有效:

     public class AccountsValidator : AbstractValidator { public AccountsValidator() { RuleFor(x => x.Accounts).SetCollectionValidator( new AccountValidator("Accounts") ); } } public class AccountValidator : AbstractValidator { public AccountValidator(string collectionName) { RuleFor(x => x) .NotEmpty() .OverridePropertyName(collectionName); } } 

    validation类:

     using FluentValidation; using System.Collections.Generic; namespace Test.Validator { public class EmailCollection { public IEnumerable email { get; set; } } public class EmailValidator: AbstractValidator { public EmailValidator() { RuleFor(x => x).Length(0, 5); } } public class EmailListValidator: AbstractValidator { public EmailListValidator() { RuleFor(x => x.email).SetCollectionValidator(new EmailValidator()); } } } 

    注意:我使用了最新的MVC 5(Nuget)版本的fluentvalidation。

    尝试使用:

     public class AccountsValidator : AbstractValidator { public AccountsValidator() { RuleForEach(x => x.Accounts).NotNull() } }