2008-12-16 34 views

回答

9

我適應找到了解決辦法,在http://blog.codeville.net/category/validation/page/2/

public class DataValidator 
    { 
    public class ErrorInfo 
    { 
     public ErrorInfo(string property, string message) 
     { 
      this.Property = property; 
      this.Message = message; 
     } 

     public string Message; 
     public string Property; 
    } 

    public static IEnumerable<ErrorInfo> Validate(object instance) 
    { 
     return from prop in instance.GetType().GetProperties() 
       from attribute in prop.GetCustomAttributes(typeof(ValidationAttribute), true).OfType<ValidationAttribute>() 
       where !attribute.IsValid(prop.GetValue(instance, null)) 
       select new ErrorInfo(prop.Name, attribute.FormatErrorMessage(string.Empty)); 
    } 
} 

這將允許您使用下面的代碼使用下面的語法來驗證任何對象:

var errors = DataValidator.Validate(obj); 

if (errors.Any()) throw new ValidationException(); 
+0

我喜歡這樣。 必須嘗試它,但它看起來像它的工作... 對Validate()的手動調用不是很好,但我們可以通過在我們的UserControls中實現 – 2009-03-04 23:05:46