How to change the default value "Field must be a number"

I am working on an MVC 3 application. One of the fields in the model is of type double and is 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; } 

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

Even the validation attribute in the Price input field has something like "data-val-number".

thanks

+6
source share
3 answers

By default, a message is called deep into the framework as a string resource. It is added by the default binder when trying to bind a string value to a double type. Therefore, if you want to change this message by default, you can write your own connecting device. Here is an example that I wrote for a DateTime type that has the same problem: fooobar.com/questions/102628 / ...

+4
source

If you agree to change only the unobtrusive side of validation, you can always specify your own jquery validation attributes:

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

Or, simply because MVC replaces the dash underscore in attribute names:

 @Html.TextBoxFor(model => model.Price, new { data_val_number = "Price must be a valid number." }) 
+14
source

It was easier for me to say:

  [RegularExpression("([0-9]+)", ErrorMessageResourceType = typeof(ErrorMessage), ErrorMessageResourceName = "NumberInvalid")] 
+3
source

Source: https://habr.com/ru/post/922228/


All Articles