在 ASP.NET MVC 中,如何验证枚举范围的整数 属性

In ASP.NET MVC, how to validate an integer property for an enumeration range

我正在用 MVC 创建 Web API。在我的 ViewModel-Objects 中,我想为整数输入创建验证,稍后在映射到一些枚举的过程中。

注意:由于项目范围之外的限制,我无法将视图模型的类型更改为实际枚举。

这是我拥有的:

[ClientValidation]
public class ContactDataObject {
    [Range(1,3)] //fixed range, bad
    public int? SalutationCd { get; set; }
}

我也可以

    [Range(/*min*/(int)Salutation.Mr, /*max*/(int)Salutation.LadiesAndGentlemen)]

这很好用,我们现在有 3 种称呼方式。但是,因为我已经知道这稍后会映射到一个枚举,所以我想做这样的事情见 [EnumDataTypeAttribute Class][1].

[ClientValidation]
public class ContactDataObject {
    [EnumDataType(typeof(Salutation))] //gives mapping error
    public int? SalutationCd { get; set; }
}

但是,用这个给出映射错误。

我想要一个属性,它只验证我的整数是否在给定枚举的值内。 如何验证枚举的(整数)

[1]: https://docs.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.enumdatatypeattribute?view=net-5.0):

您可以尝试使用自定义验证:

public class EnumValueValidationAttribute : ValidationAttribute {
    private readonly Type _enumType;

    public EnumValueValidationAttribute(Type type) {
        _enumType = type;
    }

    public override bool IsValid(object value) {
        return value != null && Enum.IsDefined(_enumType, value); //null is not considered valid
    }
}

然后像这样使用它:

    [EnumValueValidation(typeof(Salutation))]
    public int? SalutationCd { get; set; }

此 class 允许您将列 中的 基础值映射到相应的枚举常量名称。这使您可以定义一个包含与数据库值相对应的描述性值的枚举,然后在显示数据时使用枚举常量名称而不是数据库值。

[EnumDataType(typeof(ReorderLevel))]  
public object SalutationCd { get; set; }  
public class EnumValidation : ValidationAttribute
{
    private readonly Type type;

    public EnumValidation(Type type)
    {
        this.type = type;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        string message = FormatErrorMessage(validationContext.DisplayName);

        if (value == null)
            return ValidationResult.Success;

        try
        {
            if (!Enum.IsDefined(type, (int)value))
                return new ValidationResult(message);
        }
        catch (Exception ex)
        {
            return new ValidationResult(message);
        }

        return ValidationResult.Success;
    }
}

[EnumValidation(type:typeof(MemberTypeEnum), ErrorMessageResourceType = typeof(Message), ErrorMessageResourceName = "ERR_Invalid")]