Reputation: 8480
ASP.NET MVC 2 will support validation based on DataAnnotation attributes like this:
public class User
{
[Required]
[StringLength(200)]
public string Name { get; set; }
}
How can I check that a current model state is valid using only pure .NET (not using MVC binding, controller methods, etc.)?
Ideally, it would be a single method:
bool IsValid(object model);
Upvotes: 3
Views: 1621
Reputation: 28701
This code sample is from Steve Sanderson's blog about xVal (which uses the DataAnnotationsAttribute to validate properties). Basically, you just need to enumerate the attibutes using reflection and check 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);
}
}
Upvotes: 7