我怎样才能验证货币领域? [英] How can I validate a currency field?

查看:125
本文介绍了我怎样才能验证货币领域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个货币领域的ASP.NET MVC-4的应用程序:

I have an ASP.NET MVC-4 application with this currency field:

    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:c}", ConvertEmptyStringToNull = true)]
    [DataType(DataType.Currency)]
    public decimal? Price { get; set; }

这是我认为的相应部分:

This is the corresponding part in my view:

    @Html.EditorFor(model => model.Price)
    @Html.ValidationMessageFor(model => model.Price)

如果价格是100欧元在视图中的文本字段显示:

If the price is 100 Euro the text field in the view shows:

100,00€

这是很好的。

但我一旦遇到问题,我试着做一回发。验证器弹出,并说价格字段必须是一个数字。

But I am having problems as soon as I try to do a Postback. The validator pops up and says that the price field needs to be a number.

我只能解决此问题如果(1)我删除€符号和(2)更换小数点分隔符(以点代替逗号)。

I can only fix this if (1) I delete the € symbol and (2) replace the decimal separator (replace comma with a dot).

如果没有更好的解决办法,我想我可以改变DataFormatString ={0:F2},以避免货币符号。

If there is no better solution, I guess I could change the DataFormatString = "{0:F2}" in order to avoid the currency symbol.

但我怎么做校验器接受逗号作为小数点分隔符,而不是(美国)点?

But how do I make the validator accept the comma as decimal separator instead of the (American) dot?

感谢您的帮助,伙计们!

Thanks for your help, guys!

推荐答案

所以,我能够从 http://github.com/jquery/globalize

我添加下列文件到我的 /脚本文件夹:

I added the following files to my /scripts folder:


  • /scripts/globalize.js

  • /scripts/cultures/globalize.cultures.js

  • /sctipts/cultures/globalize.culture.de-DE.js

BundleConfig.cs

bundles.Add(new ScriptBundle("~/bundles/scripts/globalization").Include(
          "~/Scripts/globalize*",
          "~/Scripts/cultures/globalize*"));

_Layout.cshtml

@Scripts.Render("~/bundles/scripts/globalization")

和中的脚本部分的 _Layout.cshtml

$.validator.methods.number = function (value, element) {
            return this.optional(element) || !isNaN(Globalize.parseFloat(value));
        }
        $.validator.methods.range = function (value, element, param) {
            return this.optional(element) || (Globalize.parseFloat(value) >= param[0] && Globalize.parseFloat(value) <= param[1]);
        }

不过,我不能让货币符号与客户端的验证工作,所以我也改变了数据注解如下:

However, I couldn't make the currency symbol to work with the client validation, so I also changed the data annotation as follows:

[DisplayFormat(ApplyFormatInEditMode = false, DataFormatString = "{0:c}", ConvertEmptyStringToNull = true)]

但仅此而已。没有其他必要的修改。我现在可以输入值,如1.49或18,77,一切都被妥善保存在我的数据库。

But that was it. No other changes necessary. I can now enter values like "1,49" or "18,77" and everything gets stored properly in my database.

这篇关于我怎样才能验证货币领域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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