我有一个 MVC3 视图模型定义为:
[Validator(typeof(AccountsValidator))]
public class AccountViewModel
{
public List<string> Accounts { get; set; }
}
使用 FluentValidation (v3.3.1.0) 定义的验证为:
public class AccountsValidator : AbstractValidator<AccountViewModel>
{
public AccountsValidator()
{
RuleFor(x => x.Accounts).SetCollectionValidator(new AccountValidator()); //This won't work
}
}
并且可能会定义帐户验证:
public class AccountValidator : AbstractValidator<string> {
public OrderValidator() {
RuleFor(x => x).NotNull();
//any other validation here
}
}
我希望列表中的每个帐户都按照文档中的说明进行验证。但是,调用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"/>
}