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

相关问题