MVC/JQuery验证不接受逗号作为小数点分隔符 [英] MVC/JQuery validation does not accept comma as decimal separator

查看:88
本文介绍了MVC/JQuery验证不接受逗号作为小数点分隔符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新07.01.2018

即使有人建议,这是一个jQuery问题,而不是MVC问题,但我认为这是一个MVC问题.我已经在asp.net core 2.0 MVC中创建了整个应用程序,错误仍然存​​在.对我来说,将其链接到MVC的事实是,我可以通过在模型中添加行[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]来解决日期验证问题.因此,MVC对验证有影响.因此,我认为MVC中有某种方法可以解决此问题(请参阅此 post ).请发布asp.net core 2.0的答案.

Even though it was suggested, that this is rather a jQuery problem than an MVC problem, I think it is an MVC Problem. I've created the whole app in asp.net core 2.0 MVC and the error persist. What links it to MVC for me, is the fact that I can solve the date validation problem by adding the line [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")] to the model. Hence, MVC has an influence on the validation. So I would assume there is some way in MVC to fix this (See this post). Please post answers for asp.net core 2.0.

原始帖子

在MVC5页面中,我在文本框中渲染了Double属性.加载页面时,该值显示为,"作为小数点分隔符,这是正确的,因为该页面在德语系统上运行.如果要保存表单,则会收到验证错误.如何解决呢?我知道该主题存在一些问题,但据我所知,大多数问题已经过时了...我仍在努力,没有任何设置或任何内置选项可以让来自不同国家/地区的用户使用MVC应用.

In an MVC5 page I render a Double Property in a Textbox. When the page is loaded, the value is shown with a "," as decimal separator, which is correct, as the page runs on an German System. If I want to save the form, I get an validation error. How can this be solved? I know that there are some questions on the topic, but as far as i can see, most of them are outdated... I'm still struggling, that there is no setting or anything built-in that allows users from different countries to work with MVC apps.

型号:

[DisplayFormat(DataFormatString = "{0:n2}", ApplyFormatInEditMode = true)]
public Double Gewicht
{
    get { return gewicht; }
    set { gewicht = value; OnPropertyChanged(new PropertyChangedEventArgs("Gewicht")); }
}

CSHTML:

<div class="form-group">
    @Html.LabelFor(model => model.Gewicht, htmlAttributes: new { @class = "control-label col-md-3" })
    <div class="col-md-8">
        @Html.EditorFor(model => model.Gewicht, new { htmlAttributes = new { @class = "form-control col-md-1" } })
        @Html.ValidationMessageFor(model => model.Gewicht, "", new { @class = "text-danger" })
    </div>
</div>

Web.config

Web.config

<globalization uiCulture="de-DE" culture="de-DE" />

加载后的框->用逗号作为小数点分隔符加载的值

Box after its loaded --> Value loaded with a comma as decimal separator

单击提交按钮后的框->相同值的验证错误

Box after submit button is clicked --> Validation error for the same value

将逗号更改为点后的框->没有验证错误

Box after comma is changed to point --> No validation error

更新05.01.2018

我尝试了此处所示的解决方案不幸的是对我不起作用.但是,我还发现,这些值不仅不会被接受,而且还会更改为组分隔符和十进制分隔符混合在一起的数字(请参见图片).发生的是,值22更改为22.5并存储在数据库中.结果蜂鸣,将2,250.00的值存储到数据库中.

I've tried the solution shown here which unfortunately doesn't work for me. However, I also discovered, that the values not only get not acceptet, but are also changed to numbers where group separator and decimal separator are mixed up (see picture). What happens is, that the value of 22 gets changed to 22.5 and stored in the database. The result beeing, that a value of 2,250.00 is stored to the database.

更新07.01.2018

有趣的是,日期字段完全接受德语格式.

What is also interesting, is the fact that the date fields accept the german format perfectly fine.

财产

private DateTime? inbetriebnahmedatum;

[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime? Inbetriebnahmedatum
{
    get { return inbetriebnahmedatum; }
    set { inbetriebnahmedatum = value; OnPropertyChanged(new PropertyChangedEventArgs("Inbetriebnahmedatum")); }
}

下面显示的值被接受并处理,没有任何错误.

The value shown below is accepted and processed without any errors.

更新07.01.2018-2

如果我将

<input asp-for="Gewicht" class="form-control" />

<input name="Gewicht" id="Gewicht" type="number" class="form-control" value="@Model.Gewicht"/>

可以使用"23,7"值提交表单,而不会出现验证错误.在控制器中,绑定模型属性显示的值为"237",而IFormCollection显示的值为"23.7".这表明模型绑定程序存在问题.

The form can be submitted with the value "23,7" without validation errors. In the controller, the bound model property shows a value of "237", where as the IFormCollection shows a value of "23.7". This would suggest a problem with the model binder.

推荐答案

尽管有人建议,这是一个jQuery问题,而不是MVC问题,但我认为这是一个MVC问题.

Even though it was suggested, that this is rather a jQuery problem than an MVC problem, I think it is an MVC Problem.

不,那是不正确的.您会看到客户端验证错误,因为默认情况下,jquery.validate.js(MVC用于客户端验证的独立于第三方的独立第三方插件)会根据小数点分隔符.(点)来验证数字,不是,(逗号).

No that is no correct. You seeing a client side validation error because, by default, jquery.validate.js (an independent 3rd party plugin not associated with MicroSoft, that MVC uses for client side validation) validates numbers based on the decimal separator being a . (dot), not a , (comma).

MVC是服务器端代码,不能在浏览器中运行.为了执行客户端验证,MVC的生成表单控件的HtmlHelper方法在html中呈现了一组data-val-*属性,这些属性用于描述要执行的验证,当DOM为DOM时,这些属性又由jquery.validate.unobtrusive.js插件解析.加载,然后使用这些规则将规则添加到$.validator.

MVC is server side code and does not run in the browser. To perform client side validation, MVC's HtmlHelper methods that generate form controls render a set of data-val-* attributes in the html used to describe the validation to be performed, which are in turn parsed by the jquery.validate.unobtrusive.js plugin when the DOM is loaded, and uses those to add rules to the $.validator.

对于您的double属性,它将添加data-val-number属性(除了data-val-required属性之外),这将添加定义为number规则

In the case of your double property it will add a data-val-number attribute (in addition to data-val-required attribute), which will add the number rule which is defined as

// http://docs.jquery.com/Plugins/Validation/Methods/number
number: function( value, element ) {
    return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(value);
},

其中小数点分隔符是点,而千位分隔符是逗号(大概是因为该插件是在美国开发的,所以使用美国格式).

where the decimal separator is a dot, and the thousands separator is a comma (presumably because the plugin was developed in the US, so uses a US format).

您需要使用诸如 jquery.globalize 之类的插件来覆盖默认行为,或包含以下脚本(请注意,正则表达式只是交换点和逗号)

You need to overwrite the default behavior which you can do by using plugins such as jquery.globalize, or including the following script (note the regex just swaps the dot and comma)

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

请注意,上述脚本必须在jquery.validate.js脚本之后,但不能包装在$(document).ready()

Note the above script needs to be after the jquery.validate.js script but not wrapped in $(document).ready()

将其链接到MVC的原因是,我可以通过在模型中添加行[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]来解决日期验证问题.

What links it to MVC for me, is the fact that I can solve the date validation problem by adding the line [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")] to the model.

它实际上是与影响生成的html的[DisplayFormat]属性结合的[DataType(DataType.Date)]属性. [DataType]属性生成<input type="date" ... />,如果浏览器支持,则反过来呈现浏览器HTML-5 datepicker.根据规范,格式必须为yyyy-MM-dd(ISO格式),因此也需要[DisplayFormat]属性.

Its actually your [DataType(DataType.Date)] attribute in conjunction with the [DisplayFormat] attribute that is influencing the html that is generated. The [DataType] attribute generates <input type="date" ... /> which in turn renders the browsers HTML-5 datepicker if the browser supports it. In accordance with the specifications the format must be yyyy-MM-dd (ISO format) hence the need for the [DisplayFormat] attribute as well.

HTML-5日期选择器在浏览器区域性中呈现日期.您在输入为26.1.2018的位置显示的图像是因为您的浏览器区域性是de-DE,但是如果导航到您的站点,则由于输入的区域性是en-AU(澳大利亚),我会在输入中看到26/1/2018,并且如果某个美国用户导航到您的网站,他们会看到1/26/2018.

The HTML-5 datepicker renders the date in the browsers culture. The image you have shown where the input is 26.1.2018 is because your browser culture is de-DE, but if I navigated to your site, I would see 26/1/2018 in the input because my culture is en-AU (Australian), and if a United States user navigated to your site, they would see 1/26/2018.

客户端对date属性进行验证的原因是jquery.validate.js插件包含美国格式(MM/dd/yyyy)和ISO格式(yyyy-MM-dd)的日期规则.

The reason client side validation works for the date property is that the jquery.validate.js plugin includes date rules for both US format (MM/dd/yyyy) and ISO format (yyyy-MM-dd).

如果您要使用@Html.TextBoxFor(m => m.Inbetriebnahmedatum)(忽略您的[DataType][DisplayFormat]属性)并在输入中输入26.1.2018,您还将看到客户端验证错误.

And if you were to use @Html.TextBoxFor(m => m.Inbetriebnahmedatum) (which ignores your [DataType] and [DisplayFormat] attributes), and entered 26.1.2018 in the input, you would also see a client side validation error.

这篇关于MVC/JQuery验证不接受逗号作为小数点分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆