Is it possible to return the [Required]
attribute error message when a JSON request doesn't provide a proper value for an enum property?
For example, I have a model for a POST message that contains an AddressType
property that is an enumeration type:
public class AddressPostViewModel
{
[JsonProperty("addressType")]
[Required(ErrorMessage = "Address type is required.")]
public AddressType AddressType { get; set; }
}
The AddressType
enum accepts two values:
[JsonConverter(typeof(StringEnumConverter))]
public enum AddressType
{
[EnumMember(Value = "Dropship")]
Dropship,
[EnumMember(Value = "Shipping")]
Shipping
}
I've noticed (or actually my QA team noticed) that if the request message JSON contains either an empty string or null for the AddressType
, the error message isn't the expected Address type is required.
message. Instead, the error message is a somewhat unfriendly parsing error.
For example, if the request JSON looks like this:
{ "addressType": "" }
Then the error that is auto-generated by the validation framework looks like this:
{
"message": "Validation Failed",
"errors": [
{
"property": "addressType",
"message": "Error converting value \"\" to type 'MyNamespace.AddressType'. Path 'addressType', line 4, position 19."
}
]
}
Is there a way to ensure that error message of the [Required]
attribute is returned if someone doesn't include a valid value for an enum?