Configuring model binding error messages in ASP.NET MVC 3

I am using ASP.NET MVC 3 with Fluent Validation. I would like all of my error messages to be worded and formatted the same way, whether they be validation error messages or model binding error messages.

Say I have the following view model:

[Validator(typeof(PersonValidator))] public class Person { [ScaffoldColumn(false)] public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } } 

To test this with Fluent Validation, I can use something like this:

 public class EditorValidator : AbstractValidator<EditorModel> { public EditorValidator() { RuleFor(model => model.Month.Value).InclusiveBetween(0, 120) } } 

If the user enters "abc" for Age , this causes a model binding error, not a validation error. This is because "abc" is not an int . The system does not even get to the point that "abc" is between 0 and 120, because "abc" cannot be stored in Age .

This is good and makes sense. The problem is that the error message received is:

Field Age must be a number.

I want the message to be formatted and written as another error message issued by Fluent Validation. In this case, I would like to:

"Age" must be a number.

I understand that this is only a subtle difference, but I would like to monitor the model binding error messages.

How do I configure model binding error messages to match the error messages used by Fluent Validation?

+4
source share
2 answers

I'm not sure if there is another way to do this, but I am using Data Annotation Extensions , also available through NuGet (Install-Package DataAnnotationsExtensions.MVC3) for this exact type of thing. This package will provide you with IntegerAttribute , and from there you can specify the error message as follows:

 [Integer(ErrorMessage = "'Age' must be a number.")] public int Age { get; set; } 
+4
source

Take a look at my answer here:

How to change the check of "val-number" messages in MVC when it is generated by @Html helper

This is actually a very common question that you asked, so you should go over to stackoverflow before posting.

0
source

All Articles