I have my model:
[RegularExpression("[0-9]+", ErrorMessage = "GroupId must be a number")]
public int? GroupId { get; set; }
And WebApi application. I expect controller to return error message like this:
{
"$id": "1",
"Message": "GroupId must be a number"
}
For example, when I have Required
attribute, it works just fine:
[Required]
[StringLength(64, MinimumLength = 1, ErrorMessage = "Name must be between 1 and 64 characters long.")]
public string Name { get; set; }
{
"$id": "1",
"Message": "The Name field is required."
}
And ReqularExpression
just does not work.
I have also tried:
[RegularExpression(@"^[0-9]+$", ErrorMessage = "GroupId must be a number")]
[RegularExpression("[0-9]+", ErrorMessage = "GroupId must be a number")]
[RegularExpression(@"^([0-9]+)$", ErrorMessage = "GroupId must be a number")]
I have custom ActionFilterAttribute
on my WebApi controller.
And it creates response using HttpActionContext actionContext.modelState
.
modelState.Values[0].Errors[0].Exeption value is null
for Regex Attribute
, and the Exeption
text is "Could not convert string to integer: Path 'GroupId '.
Could someone tell me what is wrong with this?
PS
I create custom validation attribute:
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
{
int parseResult;
if (!int.TryParse(value.ToString(), out parseResult))
return new ValidationResult("Value must be a number");
}
return ValidationResult.Success;
}
Now object value
comes null
if non-numeric value was specified.
Also I tried DataAnnotationsExtensions package, it did not help.
P.S.S.
Apparently, it because model binding
takes place before validation
.
You can find more information here Server side validation of int datatype