7,765
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
using System.Text.RegularExpressions;
namespace ConsoleApplication
{
public class Model1
{
[Required]
public string Name { get; set; }
[Cust]
public int Age { get; set; }
}
class Program
{
static void Main(string[] args)
{
Model1 model = new Model1() {Name="212",Age=12345 };
foreach (var item in model.IsValid())
{
Console.WriteLine("FieldName:{0} Error Message:{1}", item.FieldName, item.Message);
}
Console.ReadLine();
}
}
public class CustAttribute : ValidationAttribute
{
public CustAttribute()
: base("应该为6位数")
{
}
public override bool IsValid(object value)
{
Regex reg=new Regex(@"[\d]{6}");
if (reg.IsMatch(Convert.ToString(value)))
{
return true;
}
else
{
return false;
}
}
}
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())
{
foreach (var validationAttribute in propertyDescriptor.Attributes.OfType<ValidationAttribute>())
{
if (!validationAttribute.IsValid(propertyDescriptor.GetValue(o)))
{
yield return new ModelValidationError() { FieldName = propertyDescriptor.Name, Message = validationAttribute.FormatErrorMessage(propertyDescriptor.Name) };
}
}
}
}
private static ICustomTypeDescriptor GetTypeDescriptor(Type type)
{
return new AssociatedMetadataTypeTypeDescriptionProvider(type).GetTypeDescriptor(type);
}
}
}
哪个attribute ? 类 属性 上面那个标记? =====木叶之夏木有JJ,另外反弹一切诅咒