using System; using System.ComponentModel.DataAnnotations; namespace LifePayment.Domain.Shared; /// <summary> /// æžšä¸¾å€¼å¼ºæ ¡éªŒ /// </summary> [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)] public class EnumValidationAttribute : ValidationAttribute { /// <summary> /// 枚举类型 /// </summary> private Type _enumType; /// <summary> /// å…许空值,有值æ‰éªŒè¯ï¼Œé»˜è®¤ false /// </summary> 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)); } }