using System.Text.RegularExpressions; namespace DataCheck; /* * 作者:icewint * */ /// /// 数据校验类 /// public class CheckData { /// /// 校验是否满足设定的规则,需要添加 特性 /// /// /// /// public static bool CheckDataRules(T data) where T : class { Type type = typeof(T); var properties = type.GetProperties(); foreach (var property in properties) { string? proValue = property.GetValue(data)?.ToString(); var attributes = property.GetCustomAttributes(false); foreach (var attribute in attributes) { if (attribute is DataRulesAttribute dataRules) { // 判断是否允许为 NULL if (!dataRules.AllowNull && proValue == null) { // 如果不允许为 null 但是为 null 了就返回错误 return false; } // 下面是允许为 null 的情况 if (proValue == null) { // 允许 null 并且为 null 满足要求 continue; } if (!Regex.IsMatch(proValue, dataRules.RegexRule)) { // 允许为 null 但不是 null 且不满足数据要求 return false; } } } } return true; } }