(以下内容转自网易博客)
上一文提到了数据验证的问题,既然提到System.ComponentModel.DataAnnotations是个好东西。自然是要试一试了。我写了一点测试代码如下:
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel.DataAnnotations; 4 5 namespace ValidateCon01 6 { 7 class Program 8 { 9 static void Main( string [] args) 10 { 11 Test1 t = new Test1(); 12 t.Age = 12 ; 13 t.Name = " 曾志伟 " ; 14 t.Note = " pppp sb aaa " ; 15 16 List < ValidationResult > vErrors = new List < ValidationResult > (); 17 ValidationContext context = new ValidationContext(t, null , null ); 18 Validator.TryValidateObject(t, context, vErrors, true ); 19 20 if (vErrors != null && vErrors.Count != 0 ) 21 { 22 foreach (var e in vErrors) 23 { 24 Console.WriteLine(e.ErrorMessage); 25 } 26 } 27 else 28 { 29 Console.WriteLine( " 实体是合法的。 " ); 30 } 31 32 Console.ReadLine(); 33 } 34 } 35 36 public class Test1 37 { 38 private int _Age = 1 ; 39 40 // 简单自定义验证 41 [CustomValidation( typeof (ValidationRules), " GE " )] 42 public int Age 43 { 44 get { return _Age; } 45 set { _Age = value; } 46 } 47 48 private string _Name = string .Empty; 49 50 // 正则表达式验证 51 [RegularExpression( " ^([刘|李]){1}.*$ " ,ErrorMessage = " 参军者必须姓刘或姓李。 " )] 52 public string Name 53 { 54 get { return _Name; } 55 set { _Name = value; } 56 } 57 58 private string _Address = string .Empty; 59 60 // 自己写Attribute完成更复杂的验证 61 [ComplexValidateAttribute] 62 public string Note 63 { 64 get { return _Address; } 65 set { _Address = value; } 66 } 67 } 68 69 public static class ValidationRules 70 { 71 public static ValidationResult GE( object data, ValidationContext context) 72 { 73 int a = ( int )data; 74 if (a > 18 ) 75 return ValidationResult.Success; 76 else 77 return new ValidationResult( " 参军者必须大于18周岁。 " ); 78 } 79 } 80 81 public class ComplexValidateAttribute : ValidationAttribute 82 { 83 public override bool IsValid( object value) 84 { 85 string msg = value.ToString(); 86 return msg.IndexOf( " sb " ) == - 1 ; 87 } 88 89 protected override ValidationResult IsValid( object value, ValidationContext validationContext) 90 { 91 string msg = value.ToString(); 92 if (msg.IndexOf( " sb " ) != - 1 ) 93 return new ValidationResult( " 包含敏感信息。验证失败。 " ); 94 else 95 return ValidationResult.Success; 96 } 97 } 98 99 }
这段代码的最终输出结果为: