views:

433

answers:

1

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);
+3  A: 

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);
    }
}
scottm
I basically did my own validation much like how the data validation attributes work on an MVC project and I basically made the same thing.
Min