如何使用Fluent验证对列表中的每个字符串进行验证?

Dan*_*ous 16 c# fluentvalidation asp.net-mvc-3

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

[Validator(typeof(AccountsValidator))]
public class AccountViewModel
{
    public List<string> Accounts { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

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

public class AccountsValidator : AbstractValidator<AccountViewModel>
{
    public AccountsValidator()
    {
        RuleFor(x => x.Accounts).SetCollectionValidator(new AccountValidator()); //This won't work
    }
}
Run Code Online (Sandbox Code Playgroud)

并且可能会定义帐户验证:

public class AccountValidator : AbstractValidator<string> {
    public OrderValidator() {
        RuleFor(x => x).NotNull();
        //any other validation here
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望列表中的每个帐户都按照文档中的描述进行修改.但是,调用SetCollectionValidator不起作用,因为在使用a时这不是一个选项,List<string>尽管如果定义为选项将存在List<Account>.我错过了什么吗?我可以改变我的模型使用List<Account>然后定义一个Account类,但我真的不想改变我的模型以适应验证.

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

@model MvcApplication9.Models.AccountViewModel

@using (Html.BeginForm())
{
    @*The first account number is a required field.*@
    <li>Account number* @Html.EditorFor(m => m.Accounts[0].Account) @Html.ValidationMessageFor(m => m.Accounts[0].Account)</li>

    for (int i = 1; i < Model.Accounts.Count; i++)
    {
        <li>Account number @Html.EditorFor(m => m.Accounts[i].Account) @Html.ValidationMessageFor(m => m.Accounts[i].Account)</li>
    }

    <input type="submit" value="Add more..." name="add"/>
    <input type="submit" value="Continue" name="next"/>
}
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 20

以下应该有效:

public class AccountsValidator : AbstractValidator<AccountViewModel>
{
    public AccountsValidator()
    {
        RuleFor(x => x.Accounts).SetCollectionValidator(
            new AccountValidator("Accounts")
        );
    }
}

public class AccountValidator : AbstractValidator<string> 
{
    public AccountValidator(string collectionName)
    {
        RuleFor(x => x)
            .NotEmpty()
            .OverridePropertyName(collectionName);
    }
}
Run Code Online (Sandbox Code Playgroud)


R.T*_*tov 5

尝试使用:

public class AccountsValidator : AbstractValidator<AccountViewModel>
{
   public AccountsValidator()
   {
       RuleForEach(x => x.Accounts).NotNull()
   }
}
Run Code Online (Sandbox Code Playgroud)