模型/資料驗證(System.ComponentModel.DataAnnotations)筆記
阿新 • • 發佈:2020-09-16
1.
、、
2.案例:(具體參照:https://www.jianshu.com/p/ca44d2ffa974)
Models:
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace WebApplication1.Models { public class UserModel { [Required(ErrorMessage = "{0} 必須填寫")] // 必須 public string UserID { get; set; } /// <summary> /// 姓名 /// </summary> [MaxLength(10, ErrorMessage = "超出字元長度")] [MinLength(2, ErrorMessage = "最短字元長度為2")] public string UserName { get; set; } /// <summary> /// 年齡 /// </summary> [Required(ErrorMessage = "{0} 必須填寫")] [Range(18, 100)] public int Age { get; set; } /// <summary> /// 性別:1表示男,2表示女 /// </summary> [RegularExpression(@"[1|2]+", ErrorMessage = "性別不正確")] // 正則規則 public int Sex { get; set; } } public class ValidResult {public List<ErrorMember> ErrorMembers { get; set; } public bool IsVaild { get; set; } } public class ErrorMember { public string ErrorMessage { get; set; } public string ErrorMemberName { get; set; } } }
邏輯層處理:
/// <summary> /// 邏輯處理 /// </summary> /// <param name="value"></param> /// <returns></returns> private static ValidResult IsValid(object value) { ValidResult result = new ValidResult(); try { var validationContext = new ValidationContext(value); var results = new List<ValidationResult>(); var isValid = Validator.TryValidateObject(value, validationContext, results, true); if (!isValid) { result.IsVaild = false; result.ErrorMembers = new List<ErrorMember>(); foreach (var item in results) { result.ErrorMembers.Add(new ErrorMember() { ErrorMessage = item.ErrorMessage, ErrorMemberName = item.MemberNames.FirstOrDefault() }); } } else { result.IsVaild = true; } } catch (Exception ex) { result.IsVaild = false; result.ErrorMembers = new List<ErrorMember>(); result.ErrorMembers.Add(new ErrorMember() { ErrorMessage = ex.Message, ErrorMemberName = "Internal error" }); } return result; }
驗證失敗處理(可以邏輯層驗證封裝成一個靜態類):
#region 邏輯處理 UserModel person = new UserModel(); person.UserID = ""; person.UserName = "K"; person.Age = 100000; person.Sex = 3000; var result = IsValid(person); if (!result.IsVaild) { // 驗證失敗處理 foreach (ErrorMember errorMember in result.ErrorMembers) { Console.WriteLine(errorMember.ErrorMemberName + ":" + errorMember.ErrorMessage); } } #endregion