简体   繁体   English

.NET:一般的DataAnnotation属性

[英].NET: DataAnnotation attributes in general

ASP.NET MVC 2 will support validation based on DataAnnotation attributes like this: ASP.NET MVC 2将支持基于DataAnnotation属性的验证,如下所示:

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.)? 如何使用纯.NET (不使用MVC绑定,控制器方法等)检查当前模型状态是否有效?

Ideally, it would be a single method: 理想情况下,它将是一个单一方法:

bool IsValid(object model);

This code sample is from Steve Sanderson's blog about xVal (which uses the DataAnnotationsAttribute to validate properties). 此代码示例来自Steve Sanderson的有关xVal博客 (该博客使用DataAnnotationsAttribute来验证属性)。 Basically, you just need to enumerate the attibutes using reflection and check IsValid() :. 基本上,您只需要使用反射来枚举服装并检查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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM