在開發中,前端的相關模型校驗每每不能知足當前開發的需求,也就是並非十分的安全。因而,不少狀況下須要後端進行模型的校驗。在.net mvc中,有不少校驗的方式(好比:值(1)能夠使用內置的標籤的校驗模式,.net中內置諸如Require/Range/Phone等校驗標籤,只需在相應的模型字段上打上對應的標籤,在相應的Action內使用ModelState.IsVaild即可以進行校驗;(2)使用FluentValidation插件(具體的使用查一下文檔便可,也比較簡單))。本文先拋開這兩款校驗組件,使用.net 提供的ValidationContext完成自定義的擴展校驗。廢話不說,直接上代碼。前端
1 public class ValidContext 2 { 3 /// <summary> 4 /// 校驗當前模型 5 /// </summary> 6 /// <param name="model"></param> 7 /// <param name="errorMsg"></param> 8 /// <param name="ignores"></param> 9 /// <returns></returns> 10 public static bool Check(object model, ref string errorMsg, IEnumerable<string> ignores = null) 11 { 12 ValidationContext context = new ValidationContext(model); 13 List<ValidationResult> results = new List<ValidationResult>(); 14 bool isVail = Validator.TryValidateObject(model, context, results, true); 15 if (isVail) 16 { 17 errorMsg = "驗證經過"; 18 return true; 19 } 20 //判斷是否有須要忽略的 21 if (ignores != null) 22 results=results.Where(o =>!ignores.Contains(o.MemberNames.FirstOrDefault())).ToList(); 23 if (results.Count > 0) 24 { 25 errorMsg = results.FirstOrDefault().ErrorMessage; 26 return false; 27 } 28 errorMsg = "驗證經過"; 29 return true; 30 31 } 32 33 34 }
1 /// <summary> 2 /// 正則表達式常量(隨時可擴展) 3 /// </summary> 4 public class PattarmConst 5 { 6 /// <summary> 7 /// 郵箱 8 /// </summary> 9 public const string IsMail = @"^\w+([-+.]\w+)@\w+([-.]\w+).\w+([-.]\w+)*$"; 10 /// <summary> 11 /// 手機號 12 /// </summary> 13 public const string IsPhone = @"^1[3|4|5|7|8|9][\d]{9}$"; 14 /// <summary> 15 /// url 16 /// </summary> 17 public const string IsUrl = @"^((https|http|ftp|rtsp|mms){0,1}(:\/\/){0,1})www\.(([A-Za-z0-9-~]+)\.)+([A-Za-z0-9-~\/])+$"; 18 /// <summary> 19 /// 漢字 20 /// </summary> 21 public const string IsChinese = @"[\u4e00-\u9fa5]"; 22 /// <summary> 23 /// 15 or 18位的身份證號 24 /// </summary> 25 public const string IsIDCard = @"^\d{15}|\d{18}"; 26 /// <summary> 27 /// 金額 28 /// </summary> 29 public const string IsPrice = @"^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$"; 30 }
1 /// <summary> 2 /// 校驗屬性自定義擴展 3 /// </summary> 4 public class RequireExt : ValidationAttribute 5 { 6 public RequireType RequireType { get; set; } 7 public override bool IsValid(object value) 8 { 9 if (value == null) 10 { 11 return false; 12 } 13 string pattarn = string.Empty; 14 switch (RequireType) 15 { 16 case RequireType.PHONE: 17 pattarn = PattarmConst.IsPhone; 18 break; 19 case RequireType.MAIL: 20 pattarn = PattarmConst.IsMail; 21 break; 22 case RequireType.URL: 23 pattarn = PattarmConst.IsUrl; 24 break; 25 case RequireType.IDCARD: 26 pattarn = PattarmConst.IsIDCard; 27 break; 28 case RequireType.PRICE: 29 pattarn = PattarmConst.IsPrice; 30 break; 31 default: 32 throw new AccessViolationException("未定義的枚舉類型"); 33 } 34 if (!Regex.IsMatch(value.ToString(), pattarn)) 35 { return false; } 36 return true; 37 } 38 } 39 /// <summary> 40 /// 校驗枚舉類型 41 /// </summary> 42 public enum RequireType 43 { 44 [Description("手機號")] 45 PHONE = 1, 46 [Description("郵箱")] 47 MAIL = 2, 48 [Description("正規URL")] 49 URL=3, 50 [Description("身份證號")] 51 IDCARD=4, 52 [Description("金額")] 53 PRICE=5 54 }