【问题标题】:DataAnnotations validation from a class来自类的 DataAnnotations 验证
【发布时间】:2011-08-23 01:27:57
【问题描述】:

我在纯 C# 应用程序的项目中使用 DataAnnotations,根据 DataAnnotations 属性验证我的模型/文档的最佳方法是什么?

【问题讨论】:

    标签: c# data-annotations


    【解决方案1】:

    现在已内置到 C# 4 中

    var result = new List<ValidationResult>();
    bool valid = Validator.TryValidateObject(Vehicle, new ValidationContext(Vehicle, null, null), result);
    

    这还将为您提供验证的详细信息。

    【讨论】:

      【解决方案2】:

      不是来自我,而是来自我的朋友史蒂夫·桑德森:

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

      您可能需要对此进行增强,例如,如果您希望 [DataType(DataType.EmailAddress)] 实际验证电子邮件地址,或者您希望支持 [MetadataType] 属性。

      【讨论】:

      • 这对我来说适用于除 DataType 之外的所有属性。例如[DataType(DataType.EmailAddress)] public object DataTypeTest { get; set; }任何想法为什么?
      猜你喜欢
      • 1970-01-01
      • 2011-01-04
      • 2012-08-23
      • 2013-06-16
      • 2011-10-31
      • 2012-10-17
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多