2025-05-22 13:06:49 +08:00
|
|
|
|
using System.Text.RegularExpressions;
|
|
|
|
|
|
|
|
|
|
|
|
namespace DataCheck;
|
|
|
|
|
|
/*
|
|
|
|
|
|
* 作者:icewint
|
|
|
|
|
|
*
|
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// 数据校验类
|
|
|
|
|
|
/// </summary>
|
|
|
|
|
|
public class CheckData
|
|
|
|
|
|
{
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// 校验是否满足设定的规则,需要添加 <see cref="DataRulesAttribute"/> 特性
|
|
|
|
|
|
/// </summary>
|
|
|
|
|
|
/// <typeparam name="T"></typeparam>
|
|
|
|
|
|
/// <param name="data"></param>
|
|
|
|
|
|
/// <returns></returns>
|
|
|
|
|
|
public static bool CheckDataRules<T>(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;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2024-05-14 16:30:56 +08:00
|
|
|
|
}
|