你如何验证对使用流利的验证列表中的每个字符串?(How do you validate agains

2019-06-23 16:38发布

我有定义为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
    }
}

我想作为描述列表中的每个帐户被valdiated 文档 。 然而,调用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"/>
}

Answer 1:

下面应该工作:

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


Answer 2:

尝试使用:

public class AccountsValidator : AbstractValidator<AccountViewModel>
{
   public AccountsValidator()
   {
       RuleForEach(x => x.Accounts).NotNull()
   }
}


Answer 3:

验证类:

using FluentValidation;
using System.Collections.Generic;

namespace Test.Validator
{

    public class EmailCollection
    {
        public IEnumerable<string> email { get; set; }

    }

    public class EmailValidator:  AbstractValidator<string>
    {
        public EmailValidator()
        {
            RuleFor(x => x).Length(0, 5);
        }

    }

    public class EmailListValidator: AbstractValidator<EmailCollection>
    {
        public EmailListValidator()
        {
            RuleFor(x => x.email).SetCollectionValidator(new EmailValidator());
        }

    }



}

注:我用fluentvalidation的最新MVC 5(的NuGet)版本。



文章来源: How do you validate against each string in a list using Fluent Validation?