C# 自定义Attribute
2021-06-12 00:03
标签:max else style owa prot err model please 长度 C# 自定义Attribute 标签:max else style owa prot err model please 长度 原文地址:https://www.cnblogs.com/allenzhang/p/10538199.html 1 // 根据不同的region 设定name不同的最大长度和提示信息Region=APAC时,Name最长可以255,其他的Region最长时30
2
3 public class QueryAddModels
4 {
5 [Required(ErrorMessage = "Please input Name")]
6 [RegularExpression(@"^([A-Za-z0-9_-]){1,300}$", ErrorMessage = "Only accept A-Z a-z 0-9 _ and -")]
7 //[MaxLength(255, ErrorMessage = "The maximum allowable length is 255")]
8 [NameMaxLength] // 自定义
9 public string Name
10 {
11 get; set;
12 }
13
14 [Required(ErrorMessage = "Please select Region")]
15 public string Region
16 {
17 get; set;
18 }
19
20 [UserIDValidation] //自定义
21 public string UserID { get; set; }
22
23 }
24
25 // NameMaxLength, Attribute
26
27 public class NameMaxLength : MaxLengthAttribute
28 {
29 protected override ValidationResult IsValid(object value, ValidationContext validationContext)
30 {
31 var region = validationContext.ObjectType.GetProperty("Region")
32 .GetValue(validationContext.ObjectInstance, null);
33
34 var name = validationContext.ObjectType.GetProperty("Name")
35 .GetValue(validationContext.ObjectInstance, null);
36
37 if (region != null)
38 {
39 if (String.Equals(region.ToString(), "APAC") && name != null && name.ToString().Length>255)
40 {
41 return new ValidationResult("The maximum allowable length is 255.");
42 }
43 else if (!String.Equals(region.ToString(), "APAC") && name != null && name.ToString().Length > 30)
44 {
45 return new ValidationResult("The maximum allowable length is 30.");
46 }
47 }
48 return ValidationResult.Success;
49 }
50 }
51
52 public class UserIDValidation : ValidationAttribute
53 {
54 protected override ValidationResult IsValid(object value, ValidationContext validationContext)
55 {
56 var newUserID = validationContext.ObjectType.GetProperty("UserID")
57 .GetValue(validationContext.ObjectInstance, null);
58
59 if (newUserID !=null && !string.IsNullOrEmpty(newUserID .ToString()))
60 {
61 if (newUserID .ToString().ToUpper() != HttpContext.Current.Session["UserID "].ToString().ToUpper())
62 return new ValidationResult("UserID can‘be changed");
63 else
64 return ValidationResult.Success;
65 }
66 return new ValidationResult("UserID can‘t be empty");
67 }
68
69 }