using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Reflection; using System.Text.RegularExpressions; namespace Zxd.Core.Shared.Helpers { public class ValidationHelper { public static List Validate(T model) where T : class, new() { var ttype = typeof(T); return Validate(ttype, model); } private static List Validate(Type ttype, object model) { var validations = new List(); var tps = ttype.GetProperties(); foreach (var tp in tps) { var valid = true; var validation = new ValidationResult { Display = tp.Name, Name = tp.Name }; var descriptionAttr = tp.GetCustomAttribute(); if (descriptionAttr != null) { validation.Display = descriptionAttr.Description; } var obj = tp.GetValue(model, null); if (obj != null) { var val = obj.ToString(); var regexAttr = tp.GetCustomAttribute(); if (regexAttr != null) { if (!Regex.IsMatch(val, regexAttr.Pattern)) { valid = false; validation.Pattern = regexAttr.Pattern; validation.Message = regexAttr.ErrorMessage; } } var maxLengthAttr = tp.GetCustomAttribute(); if (maxLengthAttr != null) { if (val.Length > maxLengthAttr.Length) { valid = false; validation.MaxLength = maxLengthAttr.Length; validation.Message = string.Format(maxLengthAttr.ErrorMessage, maxLengthAttr.Length); } } } else { var requiredAttr = tp.GetCustomAttribute(); if (requiredAttr != null) { valid = false; validation.Required = true; validation.Message = requiredAttr.ErrorMessage; } } if (!valid) { validations.Add(validation); } } return validations; } public static string Validate2(T model) where T : class, new() { var ttype = typeof(T); return Validate2(ttype, model); } public static string Validate2(object obj) { var ttype = obj.GetType(); return Validate2(ttype, obj); } private static string Validate2(Type ttype, object model) { var validations = Validate(ttype, model); var errors = string.Join(",", validations.Select(o => $"[{o.Name}]{o.Display}{o.Message}")); return errors; } } public class ValidationResult { /// /// 字段显示 /// public string Display { get; set; } /// /// 字段 /// public string Name { get; set; } /// /// 消息 /// public string Message { get; set; } /// /// 最大长度 /// public int MaxLength { get; set; } /// /// 正则模板 /// public string Pattern { get; set; } /// /// 必填 /// public bool Required { get; set; } } }