我目前有一个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 IF 上的禁用验证如何模型不需要(例如,即使我们不需要ViewModel上的属性,它仍然会触发val因此,BankInfo在任何形式的帖子上都惨遭失败)。是否有任何标准方法可以在ViewModel bind上处理w /嵌套模型验证?
答案 0 :(得分: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);
}