验证方式, 通过继承 IDataErrorInfo接口 和 DataAnnotations 解释标记语言而实现,
为了能在WPF上通用,所了也要继承属性更改通知接口INotifyPropertyChanged
实际INotifyPropertyChanged接口
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.ComponentModel; 6 7 namespace ClassLibrary1 8 { 9 public class NotifyPropertyChanged : INotifyPropertyChanged 10 { 11 #region INotifyPropertyChanged Members 12 protected void OnPropertyChanged(string name) 13 { 14 PropertyChangedEventHandler handler = PropertyChanged; 15 if (handler != null) 16 { 17 handler(this, new PropertyChangedEventArgs(name)); 18 } 19 } 20 21 public event PropertyChangedEventHandler PropertyChanged; 22 #endregion 23 } 24 }
验证核心类 继承 IDataErrorInfo和INotifyPropertyChanged的实现类
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.ComponentModel; 6 using System.ComponentModel.DataAnnotations; 7 using System.Reflection; 8 9 namespace ClassLibrary1 10 { 11 /// <summary> 12 /// 验证类和更改通知类 13 /// System.ComponentModel.DataAnnotations; 14 /// </summary> 15 /// <typeparam name="T"></typeparam> 16 public abstract class ValidationEntity<T> : NotifyPropertyChanged,IDataErrorInfo 17 { 18 public string Error 19 { 20 get { return null; } 21 } 22 23 public string this[string columnName] 24 { 25 get 26 { 27 return ValidateProperty(columnName); 28 } 29 } 30 31 /// <summary> 32 /// 验证是否通过 33 /// </summary> 34 /// <param name="errors">错误信息 ErrorMessage 值提取</param> 35 /// <returns></returns> 36 public bool Valid(ref Dictionary<string, string> errors) 37 { 38 bool result = true; 39 Type t = this.GetType(); 40 PropertyInfo[] PropertyInfo = t.GetProperties(); 41 try 42 { 43 foreach (PropertyInfo pi in PropertyInfo) 44 { 45 string name = pi.Name; 46 if (name == "Error" || name=="Item") 47 continue; 48 object value1 = pi.GetValue(this, null); 49 Dictionary<string, string> propertyErrors = new Dictionary<string, string>(); 50 if (!IsPropertyValid(value1, name, ref propertyErrors)) 51 { 52 result = false; 53 foreach (var item in propertyErrors) 54 { 55 if (!errors.ContainsKey(item.Key)) 56 { 57 errors.Add(item.Key, item.Value); 58 } 59 } 60 } 61 } 62 } 63 catch (Exception ex) 64 { 65 string aaaa = ex.Message; 66 } 67 return result; 68 } 69 70 /// <summary> 71 /// 验证属性值是否合格 72 /// </summary> 73 /// <param name="propertyName">属性名</param> 74 /// <returns></returns> 75 private string ValidateProperty(string propertyName) 76 { 77 if (string.IsNullOrEmpty(propertyName)) 78 return string.Empty; 79 object obj = this; 80 var targetType = obj.GetType(); 81 if (targetType != typeof(T)) 82 { 83 TypeDescriptor.AddProviderTransparent( 84 new AssociatedMetadataTypeTypeDescriptionProvider(targetType, typeof(T)), targetType); 85 } 86 var propertyValue = targetType.GetProperty(propertyName).GetValue(obj, null); 87 var validationContext = new ValidationContext(obj, null, null); 88 validationContext.MemberName = propertyName; 89 var validationResults = new List<ValidationResult>(); 90 Validator.TryValidateProperty(propertyValue, validationContext, validationResults); 91 if (validationResults.Count > 0) 92 { 93 return validationResults.First().ErrorMessage; 94 } 95 return string.Empty; 96 } 97 98 /// <summary> 99 /// 验证属性值 100 /// </summary> 101 /// <param name="propertyValue">属性值</param> 102 /// <param name="propertyName">属性名</param> 103 /// <param name="errors">错误信息</param> 104 /// <returns></returns> 105 private bool IsPropertyValid(object propertyValue, string propertyName, ref Dictionary<string, string> errors) 106 { 107 object obj = this; 108 TypeDescriptor.AddProviderTransparent( 109 new AssociatedMetadataTypeTypeDescriptionProvider(obj.GetType(), typeof(T)), obj.GetType()); 110 var validationContext = new ValidationContext(obj, null, null); 111 validationContext.MemberName = propertyName; 112 var validationResults = new List<ValidationResult>(); 113 Validator.TryValidateProperty(propertyValue, validationContext, validationResults); 114 if (validationResults.Count > 0 && errors == null) 115 errors = new Dictionary<string, string>(validationResults.Count); 116 foreach (var validationResult in validationResults) 117 { 118 if (!errors.ContainsKey(validationResult.MemberNames.First())) 119 errors.Add(validationResult.MemberNames.First(), validationResult.ErrorMessage); 120 } 121 if (validationResults.Count > 0) 122 return false; 123 else 124 return true; 125 } 126 127 /// <summary> 128 /// 辅助方法,把消息转成字符串 129 /// </summary> 130 /// <param name="errors">消息</param> 131 /// <returns></returns> 132 public string ErrorToString(Dictionary<string, string> errors) 133 { 134 if (errors == null || errors.Count == 0) 135 return ""; 136 StringBuilder str = new StringBuilder(); 137 foreach (var item in errors) 138 { 139 str.Append(item.Value); 140 str.Append(Environment.NewLine); 141 } 142 str.Remove(str.Length - 1, 1); 143 return str.ToString(); 144 } 145 146 147 148 } 149 }
下面是分别在mvc,wpf,winform下的使用实例