zoukankan      html  css  js  c++  java
  • 利用DataAnnotations验证实体(类)的属性

    .NET 4 和Silverlight 中可以使用以下方法:

    public static void Validate(this Entity entity)
    {
        // prepare the result
        var validationResults = new List<ValidationResult>();
        // create a validation context
        var validationContext = new ValidationContext(entity, null, null);
        // validate
        Validator.TryValidateObject(entity, validationContext, validationResults);
        // reset the validation errors of the entity
        entity.ValidationErrors.Clear();
        foreach (var error in validationResults)
            entity.ValidationErrors.Add(error);
    }
    

    .NET 3.5中的方法:

    	public static class EntityValidator
    	{
    		public static IEnumerable<ErrorField> GetErrors(object instance)
    		{
    			var t = instance.GetType();
    			var typeDescriptor = new AssociatedMetadataTypeTypeDescriptionProvider(t).GetTypeDescriptor(t);
    
    			return from prop in typeDescriptor.GetProperties().Cast<PropertyDescriptor>()
    					 from attribute in prop.Attributes.OfType<ValidationAttribute>()
    					 where !attribute.IsValid(prop.GetValue(instance))
    					 select new ErrorField(prop.Name, attribute.FormatErrorMessage(string.Empty));
    		}	
    	}
    
    	[Serializable]
    	public class ErrorField
    	{
    		public string ID { get; set; }
    		
    		public string Msg { get; set; }
    
    		public ErrorField(string id, string msg)
    		{
    			this.ID = id;
    			this.Msg = msg;
    		}
    
    
    	}
    

  • 相关阅读:
    oracle 分析函数3
    oracle 分析函数4
    oracle 分析函数2
    postgres
    博客系统
    Java 笔试面试 算法编程篇 一
    Java 笔试面试 基础篇 一
    Struts2
    mysql 数据类型
    ExceptionDemo
  • 原文地址:https://www.cnblogs.com/asyuras/p/2083805.html
Copyright © 2011-2022 走看看