2011-01-13 64 views
0

我有一個搜索表單,可以在兩個字段之一上搜索。只有一個是必需的。有沒有辦法在MVC提供的驗證中乾淨地做到這一點?我可以動態關閉MVC驗證嗎?

+0

但是,具體而言,一個是所需的路程和其他可選的路線,或者是兩者中的一個應該被填充,而不是關心哪一個? – FelixMM 2011-01-13 22:45:00

回答

0

如果這是服務器的驗證,你可以爲此創建自定義驗證屬性:

[ConditionalRequired("Field1","Field2")] 
public class MyModel() 
{ 
    public string Field1 { get; set; } 
    public string Field2 { get; set; } 
} 

然後您可以創建一個自定義的驗證屬性..類似以下內容:

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)] 
public sealed class ConditionalRequiredAttribute : ValidationAttribute 
{ 
    private const string _defaultErrorMessage = "Either '{0}' or '{1}' must be provided."; 
    public string FirstProperty { get; private set; } 
    public string SecondProperty { get; private set; } 

    public ConditionalRequiredAttribute(string first, string second) 
     : base(_defaultErrorMessage) 
    { 
     FirstProperty = first; 
     SecondProperty = second; 
    } 
    public override string FormatErrorMessage(string name) 
    { 
     return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString, 
      FirstProperty, SecondProperty); 
    } 

    public override bool IsValid(object value) 
    { 
     PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value); 
     string originalValue = properties.Find(FirstProperty, true).GetValue(value).ToString(); // ToString() MAY through a null reference exception.. i haven't tested it at all 
     string confirmValue = properties.Find(SecondProperty, true).GetValue(value).ToString(); 
     return !String.IsNullOrWhiteSpace(originalValue) || !String.IsNullOrWhiteSpace(confirmValue); // ensure at least one of these values isn't null or isn't whitespace 
    } 
} 

其有點冗長,但它使您可以靈活地將此屬性直接應用於您的模型,而不是將其應用到每個單獨的字段