quakkels quakkels - 13 days ago 5
C# Question

How to change the ErrorMessage for int model validation in ASP.NET MVC?

I have a model with a property defined like this:

[Required(ErrorMessage="Please enter how many Stream Entries are displayed per page.")]
[Range(0,250, ErrorMessage="Please enter a number between 0 and 250.")]
[Column]
public int StreamEntriesPerPage { get; set; }


This works unless the user enters something like "100q". Then a rather ugly error is displayed that says "The value '100q' is not valid for StreamEntriesPerPage."

Is there an attribute I can use to override the default error message when input is not an int?

Answer

Yes, you can use Data annotations extensions, mark your property as the following:

[Required(ErrorMessage = "Please enter how many Stream Entries are displayed per page.")]
[Range(0, 250, ErrorMessage = "Please enter a number between 0 and 250.")]
[Column]
[DataAnnotationsExtensions.Integer(ErrorMessage = "Please enter a valid number.")]
public int StreamEntriesPerPage { get; set; }