开发者

ASP.NET MVC 3 Complex Type Validation

I have a situation where I need to validate a child, but only if it exists. Basically the user can enter either a bank account or a credit card, and I only want to validate the one they enter.

Here are the Models:

public class AccountViewModel
{        
    [Required]
    public bool isBankAccount { get; set; }

    [RequiredIf("isBankAccount")]
    public BankAccount BankAccount { get; set; }

    [RequiredIf("isBankAccount",
        IfNot = true)]
    public CreditCard CreditCard { get; set; }
}

public class CreditCard
{
    [Required]
    [CreditCard]
    public string CreditCardNumber { get; set; }

    [Required]
    [Range(1, 12)]
    public int? ExpiryMonth { get; set; }

    [Required]
    [R开发者_JAVA技巧ange(2000, 3000)]
    public int? ExpiryYear { get; set; }

    [Required]
    public string CardHolderName { get; set; }
}

public class BankAccount
{
    [Required]
    public string BSB { get; set; }

    [Required]
    [StringLength(10,
        MinimumLength = 3)]
    [NumbersOnly]
    public string AccountNumber { get; set; }

    [Required]
    public string AccountHolderName { get; set; }
}

My problem is that the children's attributes are still being validated despite the parent attribute validating as true. Is there a way to stop the children from validating if the parent says so?


Why not make a property PaymentMode , derive both Bank and CC from PaymentMode, make the field required, and handle it in UI as to what user can select and enter.

Just a thought.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜