0

I have an AccountsViewModel defined as:

[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; }
}

And I have the following fluent validation:

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
    }
}

I would like to add an error against the account number if it is duplicated in the Accounts collection. However, in the AccountValidator class I do not have access to the accounts collection (as far as I am aware). How can I change/rewrite this to get access to the accounts collection so that I can ensure the account number is not duplicated?

Dangerous
  • 4,818
  • 3
  • 33
  • 48
  • It's not so fine but you could pass the collection as a parameter to the AccountValidator constructor and keep it as a local field. – ilmatte Jun 04 '12 at 09:54

1 Answers1

1

I think that your approach is slightly incorrect which is why you are struggling to do this.

Your AccountValidator should be used for validating a single instance of an account. As such your rule for "account number must be unique" should be implemented at the collection level (i.e. in your AccountsValidator). In this case, you will have access to the full collection and will be easily able to assert that each account number is unique.

Your current "not empty" rule in the AccountsValidator should also be moved to the AccountValidator.

MarkG
  • 1,859
  • 1
  • 19
  • 21