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://docs.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.enumdatatypeattribute?view=net-5.0):
question from:
https://stackoverflow.com/questions/65888263/in-asp-net-mvc-how-to-validate-an-integer-property-for-an-enumeration-range 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…