Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET: DataAnnotation attributes in general

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);
like image 558
alexey Avatar asked Nov 18 '25 19:11

alexey


1 Answers

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);
    }
}
like image 195
scottm Avatar answered Nov 20 '25 07:11

scottm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!