Search code examples
c#validationasp.net-mvc-5

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


I am creating a Web API in MVC. In my ViewModel-Objects I want to create validations for integer inputs, which are later in the process mapped to some enums.

Note: I can not change the type of the view model to an actual enum because of restrictions outside of the scope of my project.

Here's what I have:

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

And I could also do

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

This works fine, we have 3 variants of salutations right now. However, since I already know that this is later mapped to an enum, I would like to do something like this See [EnumDataTypeAttribute Class][1].

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

However, with this give a mapping error.

I would like to have an attribute, that validates only whether my interger is within the values of the given enum. How to validate for the (integer) values of the enum?

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


Solution

  • You can try using custom validation:

    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
        }
    }
    

    Then use it like:

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