using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace WebApi.Helpers
{
public class ValidationHelper
{
///
/// 验证对象的必填字段
///
/// 要验证的对象类型
/// 要验证的对象
/// 错误信息
/// 验证是否通过
public static bool ValidateRequired(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;
}
///
/// 验证对象的指定字段
///
/// 要验证的对象类型
/// 要验证的对象
/// 要验证的属性名列表
/// 错误信息
/// 验证是否通过
public static bool ValidateProperties(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;
}
}
}