5

我目前有这样的 ViewModel 设置:

public class OurViewModel
    {
        public OurViewModel() { }

        [Required]
        public int LeadID { get; set; }
        [Required]
        public int Rate { get; set; }
        [Required]
        public bool DepositRequired { get; set; }
        [RequiredIfOtherPropertyIsTrue("DepositRequired")]
        public BankInfo { get; set; }
    }

...在这种情况下,“RequiredIfOtherPropertyIsTrue”是一个验证器,它的作用与它所说的差不多:检查另一个属性是否为真(在这种情况下,我们的布尔值表示是否需要存款),而 BankInfo 是另一个看起来像这样的模型:

public class BankInfo
{
    public enum AccountTypeEnum
    {
        CHECKING,
        SAVINGS
    }

    public BankAccountInfo() { }

    [DisplayName("Account Number")]
    [Required(ErrorMessage = "You must provide a valid bank account number")]
    public String AccountNumber { get; set; }

    [DisplayName("Bank Routing Number")]
    [Required(ErrorMessage = "You must provide a valid routing number")]
    [StringLength(9, MinimumLength = 9, ErrorMessage = "Your bank routing number must be exactly 9 digits")]
    public String ABANumber { get; set; }

    [DisplayName("Bank Account Type")]
    [Required]
    public AccountTypeEnum AccountType { get; set; }

    [DisplayName("Name on Bank Account")]
    [Required(ErrorMessage = "You must provide the name on your bank account")]
    public String AccountName { get; set; }
}

现在,在我们的 ViewModel 中,我们有一个绑定到我们的 DepositRequired 布尔值的复选框,以及一个带有 BankInfo 自定义模板的 EditorFor。提交后,我们无法弄清楚如何禁用 BankInfo 上验证,如果模型不需要它(例如,即使我们不需要 ViewModel 上的属性,它仍然会触发 BankInfo 上的 val ,因此在任何形式的帖子)。是否有任何标准方法来处理 ViewModel 绑定上的嵌套模型验证?

4

1 回答 1

5

不幸的是,通过内置验证,您必须使用

ModelState.Remove("BankInfo");

有条件地忽略该对象上的任何验证失败。

如果使用 FluentValidation 是一个选项,您可以在 OurViewModelValidator 中执行以下操作:

RuleFor(ourViewModel=> ourViewModel.BankInfo).SetValidator(new BankInfoValidator()).When(ourViewModel=> ourViewModel.DepositRequired);

然后让 BankInfoValidator 处理该对象的验证。

就像是:

public class BankInfoValidator : AbstractValidator<BankInfo>
{
    public BankAccountInfoValidator() 
    {
        RuleFor(bank => bank.AccountName).NotEmpty().WithMessage("You must provide a name for your bank account.");
        RuleFor(bank => bank.AccountNumber).NotEmpty().WithMessage("You must provide an account number for your bank information.");
        RuleFor(bank => bank.AccountType).NotEmpty().WithMessage("You must select what kind of bank account you're entering information for (checking, savings).");
        RuleFor(bank => bank.ABANumber).NotEmpty().WithMessage("You must provide a routing number for your bank information.");
        RuleFor(bank => bank.ABANumber).Must(BeOnlyDigits).WithMessage("Your routing number can only contain numeric characters, 0-9.");
        RuleFor(bank => bank.AccountNumber).Must(BeOnlyDigits).WithMessage("Your account number can only contain numeric characters, 0-9.");
    }

    private bool BeOnlyDigits(string digitString)
    {
        int result;
        return int.TryParse(digitString, out result);
    }
于 2012-12-28T15:51:24.923 回答