98 lines
3.4 KiB
C#
98 lines
3.4 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Reflection;
|
|
|
|
namespace WebApi.Helpers
|
|
{
|
|
public class ValidationHelper
|
|
{
|
|
/// <summary>
|
|
/// 验证对象的必填字段
|
|
/// </summary>
|
|
/// <typeparam name="T">要验证的对象类型</typeparam>
|
|
/// <param name="obj">要验证的对象</param>
|
|
/// <param name="errorMessage">错误信息</param>
|
|
/// <returns>验证是否通过</returns>
|
|
public static bool ValidateRequired<T>(T obj, out string errorMessage)
|
|
{
|
|
errorMessage = string.Empty;
|
|
if (obj == null)
|
|
{
|
|
errorMessage = "对象不能为空";
|
|
return false;
|
|
}
|
|
|
|
var properties = typeof(T).GetProperties();
|
|
foreach (var prop in properties)
|
|
{
|
|
var value = prop.GetValue(obj);
|
|
if (value == null)
|
|
{
|
|
errorMessage = $"【{prop.Name}不能为空】";
|
|
return false;
|
|
}
|
|
//else if (prop.PropertyType == typeof(int) && (int)value == 0)
|
|
//{
|
|
// errorMessage = $"【{prop.Name}不能为0】";
|
|
// return false;
|
|
//}
|
|
else if (prop.PropertyType == typeof(string) && string.IsNullOrEmpty((string)value))
|
|
{
|
|
errorMessage = $"【{prop.Name}不能为空】";
|
|
return false;
|
|
}
|
|
else if (prop.PropertyType == typeof(object) && (object)value == null)
|
|
{
|
|
errorMessage = $"【{prop.Name}不能为空】";
|
|
return false;
|
|
}
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 验证对象的指定字段
|
|
/// </summary>
|
|
/// <typeparam name="T">要验证的对象类型</typeparam>
|
|
/// <param name="obj">要验证的对象</param>
|
|
/// <param name="propertyNames">要验证的属性名列表</param>
|
|
/// <param name="errorMessage">错误信息</param>
|
|
/// <returns>验证是否通过</returns>
|
|
public static bool ValidateProperties<T>(T obj, string[] propertyNames, out string errorMessage)
|
|
{
|
|
errorMessage = string.Empty;
|
|
if (obj == null)
|
|
{
|
|
errorMessage = "对象不能为空";
|
|
return false;
|
|
}
|
|
|
|
foreach (var propName in propertyNames)
|
|
{
|
|
var prop = typeof(T).GetProperty(propName);
|
|
if (prop == null) continue;
|
|
|
|
var value = prop.GetValue(obj);
|
|
if (value == null)
|
|
{
|
|
errorMessage = $"【{propName}不能为空】";
|
|
return false;
|
|
}
|
|
//else if (prop.PropertyType == typeof(int) && (int)value == 0)
|
|
//{
|
|
// errorMessage = $"【{propName}不能为0】";
|
|
// return false;
|
|
//}
|
|
else if (prop.PropertyType == typeof(string) && string.IsNullOrEmpty((string)value))
|
|
{
|
|
errorMessage = $"【{propName}不能为空】";
|
|
return false;
|
|
}
|
|
}
|
|
|
|
return true;
|
|
}
|
|
}
|
|
} |