2012-04-23 63 views
0

我有一個AccountsViewModel定義爲:如何使用FluentValidation驗證複雜模型並仍然可以訪問模型?

[Validator(typeof(AccountsValidator))] 
public class AccountsViewModel 
{ 
    public AccountsViewModel() 
    { 
     Accounts = new List<Account>(); 
     Accounts.Add(new Account { AccountNumber = string.Empty }); //There must be at least one account 
    } 

    public List<Account> Accounts { get; set; } 
} 

而且我有以下流利的驗證:

public class AccountsValidator : AbstractValidator<AccountsViewModel> 
{ 
    public AccountsValidator() 
    { 
     //Validate that a single account number has been entered. 
     RuleFor(x => x.Accounts[0].AccountNumber) 
      .NotEmpty() 
      .WithMessage("Please enter an account number.") 
      .OverridePropertyName("Accounts[0].AccountNumber"); 

     RuleFor(x => x.Accounts) 
      .SetCollectionValidator(new AccountValidator()); 
    } 
} 

public class AccountValidator : AbstractValidator<Account> 
{ 
    public AccountValidator() 
    { 
     RuleFor(x => x.AccountNumber) 
      .Matches(@"^\d{9}a?[0-9X]$") 
      .WithMessage("Please enter a valid account number."); 

     //TODO: Validate that the account number entered is not a duplicate account 
    } 
} 

我想如果在Accounts集合中重複對賬號添加一個錯誤。但是,在AccountValidator類中,我無權訪問帳戶集合(據我所知)。我怎樣才能改變/重寫這個訪問帳戶集合,以便我可以確保帳號不重複?

+0

這不是很好,但您可以將集合作爲參數傳遞給AccountValidator構造函數並將其保留爲本地字段。 – ilmatte 2012-06-04 09:54:30

回答

1

我認爲你的方法有點不正確,這就是爲什麼你正在努力做到這一點。

您的AccountValidator應該用於驗證帳戶的單個實例。因此,您的「賬號必須是唯一的」規則應在收款級別(即在您的AccountsValidator中)實施。在這種情況下,您將可以訪問完整收藏,並且可以輕鬆地聲明每個帳號都是唯一的。

您在AccountsValidator中的當前「非空」規則也應該移至AccountValidator。