using System;
using System.ComponentModel.DataAnnotations;
namespace LifePayment.Domain.Shared;
///
/// 枚举值强校验
///
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class EnumValidationAttribute : ValidationAttribute
{
///
/// 枚举类型
///
private Type _enumType;
///
/// 允许空值,有值才验证,默认 false
///
public bool AllowNullValue { get; set; } = false;
public EnumValidationAttribute(Type enumType)
{
if (!enumType.IsEnum) throw new ArgumentException("Type must be an enum.");
_enumType = enumType;
}
public string GetErrorMessage(string name) =>
!string.IsNullOrWhiteSpace(ErrorMessage) ? FormatErrorMessage(name) : "Enum value error.";
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
// 判断是否允许 空值
if (AllowNullValue && value == null) return ValidationResult.Success;
if (value != null && Enum.IsDefined(_enumType, value))
{
return ValidationResult.Success;
}
return new ValidationResult(GetErrorMessage(validationContext.DisplayName));
}
}