The decimal value is not valid for the price. MVC3

Product.cs

...
    [Required(ErrorMessage="Price is required")]
    [Range(0.01, 100000.00,
        ErrorMessage="Price must be between 0.01 and 100000.00")]
    public decimal Price { get; set; }
...

When I enter '89 .48 ', the form indicates the value '89 .48' for Price is invalid. I think this is due to the default language of my PC. It is not english. It is Russian. enter image description here

I tried to solve this problem haacked.com instructions:

  • I created a model of the DecimalModelBinder class and copied the code from haacked.com to the class
  • Updated Global.asax file with

    ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
    

    There is no effect. Then I tried to fix it using client side validation . 1. Added JavaScript file called "jQueryFixes.js" with code

$.validator.methods.range = function (value, element, param) {
    var globalizedValue = value.replace(",", ".");
    return this.optional(element) || (globalizedValue >= param[0] && globalizedValue <= param[1]);
}

$.validator.methods.number = function (value, element) {
    return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:[\s\.,]\d{3})+)(?:[\.,]\d+)?$/.test(value);
}

This code did not resolve this issue. Can you suggest what I'm doing wrong here?

+4
4

web.config

<system.web>
    <globalization uiCulture="en-US" culture="en-US"/>
<system.web>

,

+4

    [Required(ErrorMessage = "Price is required")]
    [Range(typeof(decimal), "0.01", "100000.00", ErrorMessage = "enter decimal value")]
    [RegularExpression(@"^\[0-9]{1,6}\.[0-9]{2}$", ErrorMessage="enter decimal value of format $9.99")]
    public decimal Price { get; set; }

.

0

DecimalModelBinder.

//if with period use InvariantCulture
if (valueResult.AttemptedValue.Contains("."))
{
    actualValue = Convert.ToDecimal(valueResult.AttemptedValue,
    CultureInfo.InvariantCulture);
}
else
{
    //if with comma use CurrentCulture
    actualValue = Convert.ToDecimal(valueResult.AttemptedValue,
    CultureInfo.CurrentCulture);
}

.

0

:

[Required(ErrorMessage = "Price is required")]
[DataType(DataType.Currency)]
public decimal Price { get; set; }    
-1

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


All Articles