Mercurial > pub > bltoolkit
comparison Source/Validation/ValidatorBaseAttribute.cs @ 0:f990fcb411a9
Копия текущей версии из github
| author | cin |
|---|---|
| date | Thu, 27 Mar 2014 21:46:09 +0400 |
| parents | |
| children |
comparison
equal
deleted
inserted
replaced
| -1:000000000000 | 0:f990fcb411a9 |
|---|---|
| 1 using System; | |
| 2 using System.Reflection; | |
| 3 using System.ComponentModel; | |
| 4 | |
| 5 namespace BLToolkit.Validation | |
| 6 { | |
| 7 public abstract class ValidatorBaseAttribute : Attribute | |
| 8 { | |
| 9 protected ValidatorBaseAttribute() | |
| 10 { | |
| 11 } | |
| 12 | |
| 13 protected ValidatorBaseAttribute(string errorMessage) | |
| 14 { | |
| 15 _errorMessage = errorMessage; | |
| 16 } | |
| 17 | |
| 18 private string _errorMessage; | |
| 19 public virtual string ErrorMessage | |
| 20 { | |
| 21 get { return _errorMessage; } | |
| 22 set { _errorMessage = value; } | |
| 23 } | |
| 24 | |
| 25 public abstract bool IsValid(ValidationContext context); | |
| 26 | |
| 27 public virtual string GetErrorMessage(ValidationContext context) | |
| 28 { | |
| 29 return string.Format(ErrorMessage, GetPropertyFriendlyName(context)); | |
| 30 } | |
| 31 | |
| 32 protected virtual string GetPropertyFriendlyName(ValidationContext context) | |
| 33 { | |
| 34 MemberInfo mi = context.MemberInfo; | |
| 35 string className = mi.DeclaringType.Name; | |
| 36 string fieldName = mi.Name; | |
| 37 | |
| 38 // Get class name. | |
| 39 // | |
| 40 object[] attrs = mi.DeclaringType.GetCustomAttributes(typeof(FriendlyNameAttribute), true); | |
| 41 | |
| 42 if (attrs.Length > 0) | |
| 43 className = ((FriendlyNameAttribute)attrs[0]).Name; | |
| 44 else | |
| 45 { | |
| 46 attrs = mi.DeclaringType.GetCustomAttributes(typeof(DisplayNameAttribute), true); | |
| 47 | |
| 48 if (attrs.Length > 0) | |
| 49 className = ((DisplayNameAttribute)attrs[0]).DisplayName; | |
| 50 } | |
| 51 | |
| 52 // Get field name. | |
| 53 // | |
| 54 attrs = mi.GetCustomAttributes(typeof(FriendlyNameAttribute), true); | |
| 55 | |
| 56 if (attrs.Length > 0) | |
| 57 fieldName = ((FriendlyNameAttribute)attrs[0]).Name; | |
| 58 else | |
| 59 { | |
| 60 attrs = mi.GetCustomAttributes(typeof(DisplayNameAttribute), true); | |
| 61 | |
| 62 if (attrs.Length > 0) | |
| 63 fieldName = ((DisplayNameAttribute)attrs[0]).DisplayName; | |
| 64 } | |
| 65 | |
| 66 return string.IsNullOrEmpty(className)? fieldName: className + "." + fieldName; | |
| 67 } | |
| 68 } | |
| 69 } |
