2010-11-18 123 views
1

我有一種情況,我需要驗證一個孩子,但只有當它存在。基本上用戶可以輸入銀行賬戶或信用卡,我只想驗證他們輸入的。ASP.NET MVC 3複雜類型驗證

下面是型號:

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] 
    [Range(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; } 
} 

我的問題是孩子們的屬性仍然被驗證,儘管父屬性驗證爲真。有沒有辦法阻止孩子們驗證父母是否這樣說?

+1

看看[使用數據註釋驗證相關屬性](http://stackoverflow.com/questions/2280539/custom-model-validation-of-dependent-properties-using-data-annotations)。 – 2010-11-18 07:24:41

回答

0

爲什麼不創建一個屬性PaymentMode,從PaymentMode派生Bank和CC,使字段成爲必需,並在UI中處理它以便用戶可以選擇和輸入。

只是一個想法。