2016-07-27 7 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

のように、文字列を渡すつもりかもしれないと思う

Areaのように実行時にのみ知られている値を渡すことはできませんか? –

+0

'Pharmacy.Area'がどこに届いているかを示す必要がありますが、一般的に' catch {return ""; } 'は解決策集合ではなく問題集合のメンバーです。 –

+0

あなたのコードはスローされた例外をすべて飲み込んでいます。 – Tim

答えて

3

属性は設計時です。あなたは私はあなたが実際にあなたのカスタム属性が実際に定義され、この

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

これらのフィールドでjqueryの検証を適用する必要がありますか?基本的に私は電話番号のために3つのテキストボックスを持っています。 1つはエリア、接頭辞、接尾辞です...私は3つのフィールドの合計が提出する前に10であることを検証しようとしています。 – thatdude

+0

@thatdude私は答えを –

+0

に編集しましたが、あなたは間違いありませんでした。私はそれを完全に見落とした。私はまだ妥当性検査を引き起こすことができませんでしたが、引用は問題を取り除きました。ありがとうございました。 – thatdude

関連する問題