2009-10-30 47 views
3

ASP.NET MVC 2屬性,基於DataAnnotation屬性像這樣將支持驗證:.NET:DataAnnotation一般

public class User 
{ 
    [Required] 
    [StringLength(200)] 
    public string Name { get; set; } 
} 

我怎麼能檢查當前的模型狀態是有效使用只有純粹。 NET(不使用MVC綁定,控制器方法等)?

在理想情況下,這將是一個方法:

bool IsValid(object model); 

回答

7

代碼樣品來自史蒂夫桑德森的blogxVal(它使用DataAnnotationsAttribute驗證屬性)。基本上,你只需要使用反射枚舉屬性並檢查IsValid():。

internal static class DataAnnotationsValidationRunner 
{ 
    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); 
    } 
} 
+0

我基本上做了我自己的驗證,很像數據驗證屬性如何在MVC項目上工作,我基本上做了同樣的事情。 – Min 2009-10-30 14:59:08