2016-07-27 101 views
-1

我有一個自定義驗證屬性,我需要傳遞一些屬性。但是,應用該屬性本身時出現了我的問題。我正在向後學習,所以我傾向於陷入「更簡單」的問題。我已經嘗試過讓這個屬性變成靜態的,但是這使我的觀點變得混亂。我該如何解決這個問題?

屬性:「對象引用是必需的非靜態字段,方法或屬性'RxCard.dataobjects.Pharmacy.Area.Get'」

public class MinimumPhoneDigits : ValidationAttribute 
    { 
     public string[] _properties; 
     public int _expectedsize; 
     public MinimumPhoneDigits(int expectedsize, params string[] properties) 
     { 
      ErrorMessage = "Not the expected size!"; 
      _properties = properties; 
      _expectedsize = expectedsize; 
     } 
     protected override ValidationResult IsValid(object value, ValidationContext validationContext) 
     { 
      if (_properties == null || _properties.Length < 1) 
      { 
       return new ValidationResult("WOAH! Not the right size."); 
      } 
      int totalsize = 0; 

      foreach (var property in _properties) 
      { 
       var propinfo = validationContext.ObjectType.GetProperty(property); 

       if (propinfo == null) 
        return new ValidationResult(string.Format("could not find {property}")); 

       var propvalue = propinfo.GetValue(validationContext.ObjectInstance, null) as string; 

       if (propvalue == null) 
        return new ValidationResult(string.Format("wrong property for {property}")); 

       totalsize += propvalue.Length; 

      } 
      if (totalsize != _expectedsize) 
       return new ValidationResult(ErrorMessage); 
      return ValidationResult.Success; 
     } 
    } 



類:

public class Pharmacy 
     {        
      [MinimumPhoneDigits(10, Area)] 
      public string PhoneNumber 
      { 
       get 
       { 
        return _phoneNumber; 
       } 
       set 
       { 
        _phoneNumber = value; 
       } 
      }  
      private string _phoneNumber; 
      public string Area 
      { 
       get 
       { 
        try 
        { 
         return _phoneNumber.Split(new char[] { '(', ')', '-' }, StringSplitOptions.RemoveEmptyEntries)[0].Trim(); 
        } 
        catch 
        { 
         return ""; 
        } 
       } 
      } 
} 
+0

哪裏是你的自定義屬性實際上定義的值? –

+0

你需要告訴我們你在哪裏獲得'Pharmacy.Area',但是,一般來說,'catch {return「」; }'是問題集的成員,而不是解決方案集的成員。 –

+0

你的代碼吞噬拋出的任何異常,順便說一句。 – Tim

回答

3

屬性是設計時。你不能傳遞只在像Area

運行時知道我想你可能實際上是打算通過一個字符串,這樣

[MinimumPhoneDigits(10, "Area")] 
+0

我應該在這些字段上應用jQuery驗證嗎?基本上我有3個電話號碼的文本框。一個用於區域,前綴,後綴...我試圖在提交之前驗證3個字段的總和是10。 – thatdude

+0

@thatdude我修改了我的答案 –

+0

你是絕對正確的。我完全忽略了這一點。我仍然無法觸發驗證,但引號排除了問題。謝謝。 – thatdude

相關問題