zhengyiming
2025-04-16 52279134e7fb09d1493561e80793e0da1d95dd41
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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));
    }
 
}