验证使用DataAnnotations类
-
13-09-2019 - |
题
我有我使用我的MVC中的数据模型中的类。我添加了一些DataAnotations,以纪念被要求的字段,我使用正则表达式来检查有效的电子邮件地址。如果该对象被调回MVC一切工作正常,我有ModelState中的属性,我可以检查以确认类是有效的,但我怎么检查,看看是否类是使用同一类和数据Anotations MVC的有效外我已经设置了?
解决方案
下面是我在与数据注释过去用来获取所有的注释对象上的错误的方法(可能使用了一些改进,但它是一个很好的起点:
public static IEnumerable<ErrorInfo> GetErrors(object instance)
{
return from prop in TypeDescriptor.GetProperties(instance).Cast<PropertyDescriptor>()
from attribute in prop.Attributes.OfType<ValidationAttribute>()
where !attribute.IsValid(prop.GetValue(instance))
select new ErrorInfo(prop.Name, attribute.FormatErrorMessage(String.Empty), instance);
}
其他提示
有没有出现任何被内置到.NET 3.5。如果你能在.NET 4的发展,但是,有一个验证类,提供你所需要的:
不隶属于 StackOverflow