Validating Nested Models

流过昼夜 提交于 2019-12-05 08:34:50

Unfortunately, with the built in validation, you'd have to use

ModelState.Remove("BankInfo");

to conditionally ignore any validation failures on that object.

If using FluentValidation is an option, you can do something like this in your OurViewModelValidator:

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

and then let the BankInfoValidator handle validation of that object.

Something like:

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);
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!