Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

c# - 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://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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...