Zxd.Core/code/Zxd.Core.Shared/Helpers/ValidationHelper.cs

134 lines
4.0 KiB
C#

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
using System.Text.RegularExpressions;
namespace Zxd.Core.Shared.Helpers
{
public class ValidationHelper
{
public static List<ValidationResult> Validate<T>(T model) where T : class, new()
{
var ttype = typeof(T);
return Validate(ttype, model);
}
private static List<ValidationResult> Validate(Type ttype, object model)
{
var validations = new List<ValidationResult>();
var tps = ttype.GetProperties();
foreach (var tp in tps)
{
var valid = true;
var validation = new ValidationResult
{
Display = tp.Name,
Name = tp.Name
};
var descriptionAttr = tp.GetCustomAttribute<DescriptionAttribute>();
if (descriptionAttr != null)
{
validation.Display = descriptionAttr.Description;
}
var obj = tp.GetValue(model, null);
if (obj != null)
{
var val = obj.ToString();
var regexAttr = tp.GetCustomAttribute<RegularExpressionAttribute>();
if (regexAttr != null)
{
if (!Regex.IsMatch(val, regexAttr.Pattern))
{
valid = false;
validation.Pattern = regexAttr.Pattern;
validation.Message = regexAttr.ErrorMessage;
}
}
var maxLengthAttr = tp.GetCustomAttribute<MaxLengthAttribute>();
if (maxLengthAttr != null)
{
if (val.Length > maxLengthAttr.Length)
{
valid = false;
validation.MaxLength = maxLengthAttr.Length;
validation.Message = string.Format(maxLengthAttr.ErrorMessage, maxLengthAttr.Length);
}
}
}
else
{
var requiredAttr = tp.GetCustomAttribute<RequiredAttribute>();
if (requiredAttr != null)
{
valid = false;
validation.Required = true;
validation.Message = requiredAttr.ErrorMessage;
}
}
if (!valid)
{
validations.Add(validation);
}
}
return validations;
}
public static string Validate2<T>(T model) where T : class, new()
{
var ttype = typeof(T);
return Validate2(ttype, model);
}
public static string Validate2(object obj)
{
var ttype = obj.GetType();
return Validate2(ttype, obj);
}
private static string Validate2(Type ttype, object model)
{
var validations = Validate(ttype, model);
var errors = string.Join(",", validations.Select(o => $"[{o.Name}]{o.Display}{o.Message}"));
return errors;
}
}
public class ValidationResult
{
/// <summary>
/// 字段显示
/// </summary>
public string Display { get; set; }
/// <summary>
/// 字段
/// </summary>
public string Name { get; set; }
/// <summary>
/// 消息
/// </summary>
public string Message { get; set; }
/// <summary>
/// 最大长度
/// </summary>
public int MaxLength { get; set; }
/// <summary>
/// 正则模板
/// </summary>
public string Pattern { get; set; }
/// <summary>
/// 必填
/// </summary>
public bool Required { get; set; }
}
}