The field must be a number

I have this field:

public decimal Price { get; set; } public decimal Price { get; set; } in the database, it is decimal (7,2).

View:

  @Html.EditorFor(model => model.Price, new { htmlAttributes = new { @class = "form-control" } }) 

If I put a semicolon, MVC does not accept by default, says: "The field must be a number" . (I tried using Regex, but not at all)

For example: 5,00, 55,00 or 555,00

Also this:

 public DateTime date { get;set; } 

View:

  @Html.EditorFor(model => model.Date, new { htmlAttributes = new { @class = "form-control" } }) 

MVC checking does not accept dates in the format dd/mm/yyyy by default, only in mm/dd/yyyy .

For example: 13/02/2015, 15/06/2013, 25/08/2012

Is there something with globalization or what? How can i solve this?

+6
source share
5 answers

One solution I found was overriding the validation functions of jquery.validate.js


 <script> $.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); } //Date dd/MM/yyyy $.validator.methods.date = function (value, element) { var date = value.split("/"); return this.optional(element) || !/Invalid|NaN/.test(new Date(date[2], date[1], date[0]).toString()); } </script> 
+8
source

You must tag your property with [DataType(DataType.Currency)] .

 [DataType(DataType.Currency)] public decimal Price { get;set;} 
+1
source

You can decorate your field with the [DisplayFormat] attribute, as shown below:

 [DisplayFormat(DataFormatString = "{0:N}", ApplyFormatInEditMode = true)] public decimal Price { get; set; } 
0
source

I have the same problem, I used it using the globalization library (globalize.js), but they changed it so that it does not include localization files. It is supposed to get them from the cldr library, but I did not understand how to do this.

0
source

You can find your answer here with a decimal point error in mvc3 - the value is not valid for the field , this did not work for me, so I used this temporary

 <div class="col-md-10"> @{ Html.EnableClientValidation(false); } @Html.EditorFor(model => model.DecimalValue, new { htmlAttributes = new { @class = "form-control" } }) @{ Html.EnableClientValidation(true); } @Html.ValidationMessageFor(model => model.DecimalValue, "", new { @class = "text-danger" }) </div> 

and I find it here ASP.NET MVC Disables client-side validation at the field level

0
source

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


All Articles