考慮下面的代碼:驗證複雜的類在MVC
public class AccountNumber
{
[AccountNumber] //This validator confirms the format of the account number
public string Value {get; set;}
public int Format { get; set;}
public string ToString()
{
return Value + " is format " + Format;
}
}
public class MyViewModel
{
public MyViewModel()
{
SourceAccount = new AccountNumber();
DestinationAccount= new AccountNumber();
}
[Required]
AccountNumber SourceAccount {get; set;}
AccountNumber DestinationAccount {get; set;}
}
然後,在我看來:
@Html.EditorFor(model => model.SourceAccount.Value)
@Html.EditorFor(model => model.DestinationAccount.Value)
基本上,我想說的是,用戶必須輸入源科目,並且他們可選地輸入目的地賬戶。但是,如果他們輸入了目的地賬戶,則其必須符合某種格式。
上述代碼的問題是,SourceAccount上的必需驗證器將始終返回有效值,因爲SourceAccount永遠不會爲null。什麼是一個很好的方法來實現我想要實現的目標?
請注意,在現實生活中,Value
的設置程序比顯示的更復雜,因爲它會以規範格式重新格式化帳戶號碼。
編輯請注意,我們必須使用內置的MVC驗證,因爲這是該項目目前使用的其餘部分。
感謝您的建議尼科。不幸的是,我們必須使用MVC驗證,因爲項目目前正在使用該驗證。我現在已經在這個問題上明確表達了。 – 2012-03-14 15:08:00