付出与汲取

根据对像属性特性,验证实体对象

/// <summary>
/// 验证实体对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
public static ResultMsg ValidateEntity<T>(T t) where T : new()
{
ResultMsg resultMsg = new ResultMsg();
try
{
PropertyInfo[] pis = t.GetType().GetProperties();
if (pis != null && pis.Length > 0)
{
object columnValue = null;
string description = string.Empty;
foreach (var item in pis)
{
//获取属性描述特性信息
object[] attr = item.GetCustomAttributes(typeof(DescriptionAttribute)).ToArray();
if (attr != null && attr.Length > 0)
{
description = ((DescriptionAttribute)((Attribute[])attr)[0]).Description;
}
else
{
description = "某个参数";
}
//判断当前属性是否为必填项
attr = item.GetCustomAttributes(typeof(RequiredAttribute)).ToArray();
columnValue = item.GetValue(t);
if (attr != null && attr.Length > 0)
{
//判断当前属性是否有值
if (columnValue == null)
{
resultMsg.ResultCode = false;
resultMsg.ErrorMsg = $"【{description}】的值不能为空!";
return resultMsg;
}
}
//判断属性长度
attr = item.GetCustomAttributes(typeof(MaxLengthAttribute)).ToArray();
if (attr != null && attr.Length > 0)
{
int maxlength = ((MaxLengthAttribute)((Attribute[])attr)[0]).Length;
//判断当前属性是否有值
if (columnValue != null && columnValue.ToString().Length > maxlength)
{
resultMsg.ResultCode = false;
resultMsg.ErrorMsg = $"【{description}】的长度不能超过【{maxlength}】!";
return resultMsg;
}
}
}
}
}
catch (Exception ex)
{
resultMsg.ResultCode = false;
resultMsg.ErrorMsg = ex.Message;
}

return resultMsg;

}

posted on 2022-04-20 15:35  付出与汲取  阅读(32)  评论(0编辑  收藏  举报

导航