How do you validate against each string in a list using Fluent Validation?

Dangerous picture Dangerous · Apr 17, 2012 · Viewed 18.9k times · Source

I have an MVC3 view model defined as:

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

With the validation defined using FluentValidation (v3.3.1.0) as:

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

And the account validation would possibly be defined:

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

I would like each account in the list to be valdiated as described in the documentation. However, the call to SetCollectionValidator doesn't work as this is not an option when using a List<string> although the option would be there if it were defined as List<Account>. Am I missing something? I could change my model to use List<Account> and then define an Account class but I don't really want to change my model to suit the validation.

For reference, this is the view that I am using:

@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"/>
}

Answer

Darin Dimitrov picture Darin Dimitrov · Apr 17, 2012

The following should work:

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