次のように定義された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
}
}
ドキュメントに記載されているように、リスト内の各アカウントを検証したいと思います。ただし、 a を使用する場合、これはオプションではないため、 への呼び出しはSetCollectionValidator
機能しませんが、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"/>
}