[英]How can I validate complex model using FluentValidation and still have access to model?
I have an AccountsViewModel defined as: 我有一个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; }
}
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. 如果
Accounts
集合中重复了Accounts
我想对帐号添加一个错误。 However, in the AccountValidator
class I do not have access to the accounts collection (as far as I am aware). 但是,在
AccountValidator
类中,我无权访问帐户集合(据我所知)。 How can I change/rewrite this to get access to the accounts collection so that I can ensure the account number is not duplicated? 如何更改/重写此密码以获得对帐户集合的访问权限,以便确保帐户号不重复?
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. 您的AccountValidator应该用于验证帐户的单个实例 。 As such your rule for "account number must be unique" should be implemented at the collection level (ie in your AccountsValidator).
因此,您的“帐号必须唯一”的规则应在收款级别(即在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. 您在AccountsValidator中当前的“非空”规则也应移至AccountValidator。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.