【问题标题】:Validating a class using DataAnnotations使用 DataAnnotations 验证类
【发布时间】:2009-12-04 15:31:48
【问题描述】:

我有一个类用于在 MVC 中对我的数据进行建模。我添加了一些 DataAnotations 来标记必填字段,并且我正在使用正则表达式来检查有效的电子邮件地址。如果对象被回发回 MVC 并且我有 ModelState 属性,我可以检查以确认该类是否有效,但我如何使用相同的类和数据注释检查该类在 MVC 之外是否有效我已经设置了吗?

【问题讨论】:

    标签: c# .net data-annotations


    【解决方案1】:

    这是我过去在数据注释中使用的一种方法,用于获取注释对象上的所有错误(它可以进行一些改进,但这是一个很好的起点:

    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);    
    }
    

    【讨论】:

      【解决方案2】:

      .NET 3.5 中似乎没有内置任何内容。但是,如果您可以针对 .NET 4 进行开发,那么有一个 Validator 类可以满足您的需求:

      Validator class on MSDN

      【讨论】:

        猜你喜欢
        • 2011-01-04
        • 2012-08-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-31
        • 2010-12-17
        • 2023-03-03
        相关资源
        最近更新 更多