ASP.NET Core Web API - How to validate based on specified value using data annotation

Viewed 55

In ASP.NET Core-6 Web API, I just decide to use data annotation for validation. I have this code:

public class EnumList
{
    public enum ChargeMode : byte
    {
        None = 0,
        Fixed = 1,
        Percentage = 2
    }
}

DTO:

public class CustomerDto
{
    [Required]
    public ChargeMode ChargeMode { get; set; }     // None = 0, Fixed = 1, Percentage = 2
}

How do I validate ChargeMode in the CustomerDto based on any of the values coming from ChargeMode coming from EnumList?

Thanks

1 Answers

If you post a value don't match the format you'll get 400 error

but if you pass an int value out of range,you'll get the value you send rather than"None","Fixed","Percentage"

So You could try add [Range(0, 2,ErrorMessage = "Value for {0} must be between {1} and {2}.")] Attribute to prevent the value out of range

enter image description here

Related