10

I'm working on an MVC 3 application. One of the fields in the model is of type double and defined as follows:

    [Required(ErrorMessageResourceName = "ListingItemPriceRequired", ErrorMessageResourceType = typeof(ErrorMessages))]
    [Display(Name = "DisplayListingItemPrice", ResourceType = typeof(Display))]
    [Range(1, 500000000, ErrorMessageResourceName = "ListingItemPriceNotWithinRange", ErrorMessageResourceType = typeof(ErrorMessages))]
    public double Price { get; set; }

Still, when I enter a value of a number with some trailing spaces like "342 ", I get the default message "The field price must be a number".

Even the validation attribute on the Price input field has something as "data-val-number".

Thanks

Bill
  • 2,026
  • 9
  • 55
  • 99

3 Answers3

17

If you're ok with changing just the unobtrusive validation side of things, you can always supply your own jquery validation attributes:

@Html.TextBoxFor(model => model.Price, new Dictionary<string, object>() { { "data-val-number", "Price must be a valid number." } })

Or, the following is simpler as MVC replaces underscores with dashes in attribute names:

@Html.TextBoxFor(model => model.Price, new { data_val_number = "Price must be a valid number." })
ScottE
  • 21,530
  • 18
  • 94
  • 131
6

The default message is baked deeply into the framework, as a string resource. It is added by the default model binder when trying to bind the string value to a double type. So if you want to change this default message you could write a custom model binder. Here's an example I wrote for the DateTime type which has the same issue: https://stackoverflow.com/a/7836093/29407

Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Thanks Darin. For each data type there is a model binder? btw, do you have a blog? – Bill Aug 06 '12 at 18:52
  • 3
    I implemented a custom model binder, but still on the client side, the same sentence is displayed, the default one. How to inject another message even on client side? Thanks – Bill Aug 07 '12 at 10:13
6

I found it easier to just say:

 [RegularExpression("([0-9]+)", ErrorMessageResourceType = typeof(ErrorMessage), ErrorMessageResourceName = "NumberInvalid")]
Nick
  • 2,877
  • 2
  • 33
  • 62