【问题标题】:How can I validate complex model using FluentValidation and still have access to model?如何使用 FluentValidation 验证复杂模型并且仍然可以访问模型?
【发布时间】:2012-04-23 16:00:53
【问题描述】:

我有一个 AccountsViewModel 定义为:

[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 类中,我无权访问帐户集合(据我所知)。如何更改/重写此内容以访问帐户集合,以确保帐号不重复?

【问题讨论】:

  • 这不是很好,但您可以将集合作为参数传递给 AccountValidator 构造函数并将其保留为本地字段。

标签: c# asp.net-mvc-3 fluentvalidation


【解决方案1】:

我认为你的方法有点不正确,这就是你努力做到这一点的原因。

您的 AccountValidator 应用于验证帐户的单个实例。因此,您的“帐号必须是唯一的”规则应在 collection 级别(即在您的 AccountsValidator 中)实施。在这种情况下,您将可以访问完整的集合,并且可以轻松地断言每个帐号都是唯一的。

您当前在 AccountsValidator 中的“非空”规则也应移至 AccountValidator。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-12
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    • 1970-01-01
    相关资源
    最近更新 更多