2011-03-30 159 views
0

是否有可能在ASP.NET MVC中的一個字段上的CustomValidationAttribute只有在不同的CustomValidationAttribute驗證不同字段時才能執行。自定義驗證屬性ASP.NET MVC

我的看法需要包含單獨的日期和時間字段。我有兩個單獨的自定義驗證屬性。但是,是否有可能僅在日期驗證屬性驗證爲true時才檢查時間驗證屬性?

謝謝。

+0

爲什麼你想這樣做?如果日期和時間都無效,爲什麼不這樣說呢?或者爲什麼不使用客戶端驗證來做到這一點,這將做你想要的? – arame3333 2011-03-30 07:11:15

回答

3

時驗證屬性檢查 只有當日期驗證屬性 驗證爲真?

此聲明表示自定義驗證。是的,你可以做到這一點。您可以定義將其他字段的名稱作爲參數的自定義驗證屬性。然後,在重寫的Validate()方法中,您可以通過名稱獲取其他字段的PropertyInfo,然後獲取驗證屬性並驗證它們。得到結果後,您可以決定是否對第一個字段進行驗證。 Brad Wilson上mvcConf有很大的職位有關驗證

順便問一下,你也可以實現IClientValidatable收官客戶端驗證

這是非常非常的示例代碼,它需要一些參數檢查和錯誤處理等。但我認爲想法很清楚

public class OtherFieldDependentCustomValidationAttribute : ValidationAttribute 
{ 
    public readonly string _fieldName; 

    public OtherFieldDependentCustomValidationAttribute(string otherFieldName) 
    { 
     _fieldName = otherFieldName; 
    } 

    protected override System.ComponentModel.DataAnnotations.ValidationResult IsValid(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext) 
    { 
     //Get PropertyInfo For The Other Field 
     PropertyInfo otherProperty = validationContext.ObjectType.GetProperty(_fieldName); 

     //Get ValidationAttribute of that property. the OtherFieldDependentCustomValidationAttribute is sample, it can be replaced by other validation attribute 
     OtherFieldDependentCustomValidationAttribute attribute = (OtherFieldDependentCustomValidationAttribute)(otherProperty.GetCustomAttributes(typeof(OtherFieldDependentCustomValidationAttribute), false))[0]; 

     if (attribute.IsValid(otherProperty.GetValue(validationContext.ObjectInstance, null), validationContext) == ValidationResult.Success) 
     { 
      //Other Field Is valid, do some custom validation on current field 

      //custom validation.... 

      throw new ValidationException("Other is valid, but this is not"); 
     } 
     else 
     { 
      //Other Field Is Invalid, do not validate current one 
      return ValidationResult.Success; 
     } 
    } 
} 
+0

@archil:你能給一些僞代碼嗎?我無法完全跟隨你。 – Jake 2011-03-30 07:17:43

+0

你檢查了我提到的布萊德威爾遜的視頻嗎? – archil 2011-03-30 07:19:57

+0

是的,我做了,該視頻是基於mvc 3,我正在開發的項目需要使用mvc 2 – Jake 2011-03-30 07:25:57