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 ?

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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 stackoverflow.com/questions/12240713/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.