.NET: DataAnnotation Attributes in General

ASP.NET MVC 2 will support DataAnnotation attribute-based validation as follows:

public class User
{
    [Required]
    [StringLength(200)]
    public string Name { get; set; }
}

How to verify that the current state of the model is valid using only pure .NET (without using MVC binding, controller methods, etc.)?

Ideally, this would be the only method:

bool IsValid(object model);
+3
source share
1 answer

blog xVal ( DataAnnotationsAttribute ). , attibutes 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);
    }
}
+7

Source: https://habr.com/ru/post/1721502/


All Articles