Yoda
Yoda

Reputation: 18068

How to validate enum in DTO so it contains valid values for that enum type?

I have a DTO:

public class MyDto
{
    [Required]
    [Range(1, int.MaxValue)]
    public MyEnum MyEnum { get; set; }
}
public enum MyEnum
{
    E1 = 1,
    E2 = 2 << 0,
    E3 = 2 << 1,
    E4 = 2 << 2,
}

When the the request with empty body {} is being sent to the method with a signature: public async Task<IActionResult> Method([FromBody] MyEnum value)

the MyEnum would default to 0 which is not valid value for that enum. That is why I introduced [Range(1, int.MaxValue)] annotation. But still if request looks like this:

{"MyEnum" : 3} the [FromBody] will just construct MyDto with that invalid value of 3.

Question: How I make [FromBody] to fail model validation when request contains value that is invalid for MyEnum, the only valid values are E1,E2,E3,E4,1,2,4,8,16?

Upvotes: 1

Views: 2188

Answers (1)

Yoda
Yoda

Reputation: 18068

Ok, I found it:

    [Required]
    [EnumDataType(typeof(MyEnum))]
    public MyEnum MyEnum { get; set; }

Upvotes: 3

Related Questions