2010-07-21 62 views
3

有人可以幫我解決這個問題。我試圖弄清楚如何檢查表格上的兩個值,必須填寫兩項中的一項。如何進行檢查以確保其中一項或兩項都已輸入?驗證屬性MVC 2 - 檢查兩個值之一

我使用的ViewModels在ASP.NET MVC 2

這裏的代碼有點剪斷:

的觀點:

Email: <%=Html.TextBoxFor(x => x.Email)%> 
Telephone: <%=Html.TextBoxFor(x => x.TelephoneNumber)%> 

視圖模型:

[Email(ErrorMessage = "Please Enter a Valid Email Address")] 
    public string Email { get; set; } 

    [DisplayName("Telephone Number")] 
    public string TelephoneNumber { get; set; } 

我希望提供這些細節中的任何一個。

感謝您的指點。

回答

5

您或許可以以與作爲File-> New-> ASP.NET MVC 2 Web應用程序一部分的PropertiesMustMatch屬性非常相似的方式來執行此操作。

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)] 
public sealed class EitherOrAttribute : ValidationAttribute 
{ 
    private const string _defaultErrorMessage = "Either '{0}' or '{1}' must have a value."; 
    private readonly object _typeId = new object(); 

    public EitherOrAttribute(string primaryProperty, string secondaryProperty) 
     : base(_defaultErrorMessage) 
    { 
     PrimaryProperty = primaryProperty; 
     SecondaryProperty = secondaryProperty; 
    } 

    public string PrimaryProperty { get; private set; } 
    public string SecondaryProperty { get; private set; } 

    public override object TypeId 
    { 
     get 
     { 
      return _typeId; 
     } 
    } 

    public override string FormatErrorMessage(string name) 
    { 
     return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString, 
      PrimaryProperty, SecondaryProperty); 
    } 

    public override bool IsValid(object value) 
    { 
     PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value); 
     object primaryValue = properties.Find(PrimaryProperty, true /* ignoreCase */).GetValue(value); 
     object secondaryValue = properties.Find(SecondaryProperty, true /* ignoreCase */).GetValue(value); 
     return primaryValue != null || secondaryValue != null; 
    } 
} 

該函數的關鍵部分是IsValid函數,用於確定兩個參數之一是否有值。

不同於一般的基於屬性的屬性,這適用於類級別,並且可以像這樣使用:

[EitherOr("Email", "TelephoneNumber")] 
public class ExampleViewModel 
{ 
    [Email(ErrorMessage = "Please Enter a Valid Email Address")] 
    public string Email { get; set; } 

    [DisplayName("Telephone Number")] 
    public string TelephoneNumber { get; set; } 
} 

你應該能夠儘可能多地每個表單需要添加這些,但如果你想迫使他們輸入一個值到兩個以上的框(例如電子郵件,電話或傳真)中的一個,那麼你可能會最好地改變輸入爲更多的值的數組,並解析它。