您的位置:首页 > 编程语言 > C#

C# 通用验证类 支持 WPF,MVC,Winform

2013-07-08 15:58 239 查看
验证方式, 通过继承 IDataErrorInfo接口 和 DataAnnotations 解释标记语言而实现,

为了能在WPF上通用,所了也要继承属性更改通知接口INotifyPropertyChanged

实际INotifyPropertyChanged接口

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Reflection;

namespace ClassLibrary1
{
/// <summary>
/// 验证类和更改通知类
/// System.ComponentModel.DataAnnotations;
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class ValidationEntity<T> : NotifyPropertyChanged,IDataErrorInfo
{
public string Error
{
get { return null; }
}

public string this[string columnName]
{
get
{
return ValidateProperty(columnName);
}
}

/// <summary>
/// 验证是否通过
/// </summary>
/// <param name="errors">错误信息  ErrorMessage 值提取</param>
/// <returns></returns>
public bool Valid(ref Dictionary<string, string> errors)
{
bool result = true;
Type t = this.GetType();
PropertyInfo[] PropertyInfo = t.GetProperties();
try
{
foreach (PropertyInfo pi in PropertyInfo)
{
string name = pi.Name;
if (name == "Error" || name=="Item")
continue;
object value1 = pi.GetValue(this, null);
Dictionary<string, string> propertyErrors = new Dictionary<string, string>();
if (!IsPropertyValid(value1, name, ref propertyErrors))
{
result = false;
foreach (var item in propertyErrors)
{
if (!errors.ContainsKey(item.Key))
{
errors.Add(item.Key, item.Value);
}
}
}
}
}
catch (Exception ex)
{
string aaaa = ex.Message;
}
return result;
}

/// <summary>
/// 验证属性值是否合格
/// </summary>
/// <param name="propertyName">属性名</param>
/// <returns></returns>
private string ValidateProperty(string propertyName)
{
if (string.IsNullOrEmpty(propertyName))
return string.Empty;
object obj = this;
var targetType = obj.GetType();
if (targetType != typeof(T))
{
TypeDescriptor.AddProviderTransparent(
new AssociatedMetadataTypeTypeDescriptionProvider(targetType, typeof(T)), targetType);
}
var propertyValue = targetType.GetProperty(propertyName).GetValue(obj, null);
var validationContext = new ValidationContext(obj, null, null);
validationContext.MemberName = propertyName;
var validationResults = new List<ValidationResult>();
Validator.TryValidateProperty(propertyValue, validationContext, validationResults);
if (validationResults.Count > 0)
{
return validationResults.First().ErrorMessage;
}
return string.Empty;
}

/// <summary>
/// 验证属性值
/// </summary>
/// <param name="propertyValue">属性值</param>
/// <param name="propertyName">属性名</param>
/// <param name="errors">错误信息</param>
/// <returns></returns>
private bool IsPropertyValid(object propertyValue, string propertyName, ref Dictionary<string, string> errors)
{
object obj = this;
TypeDescriptor.AddProviderTransparent(
new AssociatedMetadataTypeTypeDescriptionProvider(obj.GetType(), typeof(T)), obj.GetType());
var validationContext = new ValidationContext(obj, null, null);
validationContext.MemberName = propertyName;
var validationResults = new List<ValidationResult>();
Validator.TryValidateProperty(propertyValue, validationContext, validationResults);
if (validationResults.Count > 0 && errors == null)
errors = new Dictionary<string, string>(validationResults.Count);
foreach (var validationResult in validationResults)
{
if (!errors.ContainsKey(validationResult.MemberNames.First()))
errors.Add(validationResult.MemberNames.First(), validationResult.ErrorMessage);
}
if (validationResults.Count > 0)
return false;
else
return true;
}

/// <summary>
/// 辅助方法,把消息转成字符串
/// </summary>
/// <param name="errors">消息</param>
/// <returns></returns>
public string ErrorToString(Dictionary<string, string> errors)
{
if (errors == null || errors.Count == 0)
return "";
StringBuilder str = new StringBuilder();
foreach (var item in errors)
{
str.Append(item.Value);
str.Append(Environment.NewLine);
}
str.Remove(str.Length - 1, 1);
return str.ToString();
}

}
}


View Code

下面是分别在mvc,wpf,winform下的使用实例
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: