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 Name10 {11 get; set;12 }13 14 [Required(ErrorMessage = "Please select Region")]15 public string Region16 {17 get; set;18 }19 20 [UserIDValidation] //自定义21 public string UserID { get; set; }22 23 }24 25 // NameMaxLength, Attribute 26 27 public class NameMaxLength : MaxLengthAttribute28 { 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 : ValidationAttribute53 {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 else64 return ValidationResult.Success;65 }66 return new ValidationResult("UserID can‘t be empty");67 }68 69 }