标签:
貌似没听过,但肯定见过
所属程序集:System.ComponentModel.DataAnnotations
DataAnnotation code:
public class Product { [Required] [StringLength(10,MinimumLength =5)] public string Name { get; set; } [Required] public decimal? UnitPrice { get; set; } }
没错,就是给类的属性加上描述性的验证信息,
当然是先自己想办法了,
添加辅助类:
public class ModelValidationError { public string FieldName { get; set; } public string Message { get; set; } } public static class DataAnnotationHelper { public static IEnumerable<ModelValidationError> IsValid<T>(this T o) { var descriptor = GetTypeDescriptor(typeof(T)); foreach (PropertyDescriptor propertyDescriptor in descriptor.GetProperties()) { var validations = propertyDescriptor.Attributes.OfType<ValidationAttribute>(); foreach (var validationAttribute in validations) { var v = propertyDescriptor.GetValue(o); if (!validationAttribute.IsValid(v)) { yield return new ModelValidationError() { FieldName = propertyDescriptor.Name, Message = validationAttribute.FormatErrorMessage(propertyDescriptor.Name) }; } } } } private static ICustomTypeDescriptor GetTypeDescriptor(Type type) { return new AssociatedMetadataTypeTypeDescriptionProvider(type).GetTypeDescriptor(type); } }
如何使用:
class Program { static void Main(string[] args) { Product product = new Product(); foreach (var item in product.IsValid()) { Console.WriteLine("FieldName:{0} Error Message:{1}", item.FieldName, item.Message); } Console.ReadKey(); } }
.net 提供的 ValidateAttribute不够用怎么搞?自定义呗,
public class PriceAttribute : ValidationAttribute { public double MinPrice { get; set; } public override bool IsValid(object value) { if (value == null) { return false; } var price = (double)value; if (price < MinPrice) { return false; } return true; } public override string FormatErrorMessage(string name) { return "Min Price is "+MinPrice; } }
使用方法和.net 提供的一样:
public class Product { [Required] [StringLength(10,MinimumLength =5)] public string Name { get; set; } [Required] [Price(MinPrice =2)] public decimal? UnitPrice { get; set; } }
实际应用中遇到的问题:
在使用EF DBfirst的时候,实体类的validate attribute,一不小心经常会被覆盖掉,如何解决
巧妙使用partial 类
public class ProductMetaData { [Required] [StringLength(10, MinimumLength = 5)] public string Name { get; set; } [Required] [Price(MinPrice = 2)] public decimal? UnitPrice { get; set; } } [MetadataType(typeof(ProductMetaData))] public partial class Product { } public partial class Product { public string Name { get; set; } public decimal? UnitPrice { get; set; } }
asp.net mvc中对data annotation具有原生的支持,
标签:
原文地址:http://www.cnblogs.com/Leo_wl/p/5602367.html