Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"/>
}
like image 944
Dangerous Avatar asked Apr 17 '12 11:04

Dangerous


2 Answers

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);
    }
}
like image 126
Darin Dimitrov Avatar answered Oct 26 '22 10:10

Darin Dimitrov


Try to use:

public class AccountsValidator : AbstractValidator<AccountViewModel>
{
   public AccountsValidator()
   {
       RuleForEach(x => x.Accounts).NotNull()
   }
}
like image 37
R.Titov Avatar answered Oct 26 '22 10:10

R.Titov