Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 573
quakkels Avatar asked Jul 05 '11 19:07

quakkels


People also ask

What replaces Valmsg data?

The data-valmsg-for 's value is the name (not the id ) of the input it refers to, and data-valmsg-replace="true" just means that the default message should be replaced, for example you could have a default message for the email field: <span class="field-validation-valid" data-valmsg-for="email" data-valmsg-replace=" ...

What is the use of ModelState IsValid in MVC?

ModelState. IsValid indicates if it was possible to bind the incoming values from the request to the model correctly and whether any explicitly specified validation rules were broken during the model binding process.


2 Answers

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; } 
like image 171
Feras Kayyali Avatar answered Sep 24 '22 05:09

Feras Kayyali


Try adding

[RegularExpression("\\d+", ErrorMessage = "some message here")] 

Reference blog post

like image 38
Bala R Avatar answered Sep 20 '22 05:09

Bala R