0

I have a model on which I'm using validation by data annotations, like this :

public int Id { get; set; }

[Required(ErrorMessage = "Please enter the Sample Description.")]
public string Description { get; set; }

[Required(ErrorMessage = "Please enter the Start Date.")]
[DataType(DataType.Date)]
public DateTime StartDate { get; set; }

Data gets inserted via an API and, if validation fails, I would like to take any returned error messages and put them directly out to the screen.

This is fine for something like this :

[Required(ErrorMessage = "Please enter the Sample Description.")]
public string Description { get; set; }

But in the case of the integer property shown, "Id", and the client sending, a value that can't be cast to an integer, for instance "x", then you get returned a low level message like this :

"Could not convert string to integer: x. Path 'Id', line 1, position 9.

What I really want is a message more like

"Please provide an integer for the Id".

Is there anyway to allow data validation by annotation and still provide a more useful message than what I'm getting ?

glaucon
  • 8,112
  • 9
  • 41
  • 63

1 Answers1

0

Few possible options:

(1) In MVC 4 you can change the error message in the View with Html.ValidationMessageFor. Like:

@Html.ValidationMessageFor(model => model.YourIntField, "Please provide an integer for the Id".)

In model:

[DataType(DataType.Int)] public int YourIntField { get; set; }

(2) For any number validation you have to use different different range validation as per your requirements

For Integer

[Range(0, int.MaxValue, ErrorMessage = "Please enter valid integer Number")]

For Float:

[Range(0, float.MaxValue, ErrorMessage = "Please enter valid float Number")]

Ref: Int or Number DataType for DataAnnotation validation attribute

Community
  • 1
  • 1
Sami
  • 3,686
  • 4
  • 17
  • 28
  • Thanks for your response. When I try the second of your approaches I get the same error message as I did previously (""Could not convert string to integer: x. Path 'Id', line 1, position 9."). I'm not sure whether the first option is applicable to me. I don't actually have views - just models and controllers. The controllers responds to requests and return JSON. If you could expand on the first maybe I could try that ? Thanks again. – glaucon Aug 08 '16 at 00:02
  • If you don't have views then you need to check this on Controller level, because DataAnnotations results are rendered on View. You can return HttpResponse ... have a look at http://stackoverflow.com/questions/12240713/put-content-in-httpresponsemessage-object – Sami Aug 08 '16 at 01:04