Question

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);
Was it helpful?

Solution

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);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top