William Calleja
William Calleja

Reputation: 4175

How can I remove MVC2's validation messages?

I am using ASP.NET C# MVC2 and I have the following field within a model with the following data annotation validation attributes:

[DisplayName("My Custom Field")]
[Range(long.MinValue, long.MaxValue, ErrorMessage = "The stated My Custom Field value is invalid!")]
public long? MyCustomField{ get; set; }

In the form this field should allow the user to leave it blank and display a validation message should the user attempt to enter a value that cannot be expressed as a number. From a validation point of view, this is working as intended and displaying the following error messages:

The stated My Custom Field value is invalid!

The field My Custom Field must be a number.

The first validation message is the custom validation message that I wrote and the second validation message is the one the MVC2 automatically generates. I need to get rid of the second one since its redundant. How do I do this? In my view I have the following markup

<% Html.EnableClientValidation(); %>
<% using (Html.BeginForm())
   { %>
   <%:Html.ValidationSummary(false)%>
   <% Html.ValidateFor(m => m.MyCustomField); %>

Upvotes: 3

Views: 207

Answers (1)

Andras Zoltan
Andras Zoltan

Reputation: 42333

This issue you have here is because the property being bound is a numeric, and model binding is automatically handling the fact that the string could not be converted to a number. It's not the RangeAttribute's doing.

You might instead consider having a new property as a string and deriving your own RangeAttribute which works at the string level, parsing the number first.

Then you have your existing property wrap that string:

 [DisplayName("My Custom Field")]
 [MyCustomRangeAttribute(/* blah */)] //<-- the new range attribute you write
 public string MyCustomFieldString
 {
   get; set;
 }

 public int? MyCustomField
 {
   get 
   { 
     if(string.IsNullOrWhiteSpace(MyCustomField))
       return null;
     int result;
     if(int.TryParse(MyCustomField, out result))
       return result;
     return null;
   }    
   set
   {
      MyCustomFieldString = value != null ? value.Value.ToString() : null;
   }
 }

Your code can continue to work on the int? property quite happily, but - all model binding is done on the string property.

You will also ideally add [Bind(Exclude"MyCustomField")] to the model type - to ensure that MVC doesn't try and bind the int? field. Or you can just make it internal. If it's in the web project and you only need to reference it in the web project.

You could also consider the really hacky approach - and finding that error in your controller method via ModelState.Errors and removing it before you return your view result...

Upvotes: 2

Related Questions