MVC 3 jQuery 验证/数字/十进制字段的全球化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5199835/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:43:36  来源:igfitidea点击:

MVC 3 jQuery Validation/globalizing of number/decimal field

jqueryvalidationasp.net-mvc-3globalizationculture

提问by designvision.dk

When using globalization culture="da-DK" in the Web.config file, the jQuery validation does not work.

在 Web.config 文件中使用 globalculture="da-DK" 时,jQuery 验证不起作用。

In Denmark, we use the notation 19,95 instead of the US way 19.95 when we write a price for at product, and that have given me a problem, that I can't solve.

在丹麦,当我们为 at 产品写价格时,我们使用符号 19,95 而不是美国方式 19.95,这给了我一个我无法解决的问题。

I've started VS2010, new MVC 3 project, added a homeController, a Product class, and a simple standard edit view and the error is already there.

我已经启动了 VS2010,新的 MVC 3 项目,添加了一个 homeController、一个 Product 类和一个简单的标准编辑视图,并且错误已经存在。

Product Class:

产品类别:

public class Product
{
    public string name { get; set; }
    public string itemNo { get; set; }
    public decimal price { get; set; }
}

HomeController:

家庭控制器:

public class homeController : Controller
{
    public ActionResult Index()
    {
        var product1 = new Product { name = "Testproduct", itemNo = "PRD-151541", price = 19 };
        return View(product1);
    }
}

Index View:

索引视图:

@model WebUI.DomainModel.Product

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Product</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.name)
            @Html.ValidationMessageFor(model => model.name)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.itemNo)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.itemNo)
            @Html.ValidationMessageFor(model => model.itemNo)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.price)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.price)
            @Html.ValidationMessageFor(model => model.price)
        </div>

        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
}

The result:

结果:

Unfortunately I can't submit an image here - so please follow this link to see the result: http://www.designvision.dk/temp/mvc3_razor_validation_error.gif

不幸的是,我无法在此处提交图像 - 所以请点击此链接查看结果:http: //www.designvision.dk/temp/mvc3_razor_validation_error.gif

SO - when running the website, the field will be set to 19,00 - which IS the correct culture definition - but when trying to save, validation fails.

所以 - 运行网站时,该字段将设置为 19,00 - 这是正确的文化定义 - 但在尝试保存时,验证失败。

Please help...

请帮忙...

采纳答案by Darin Dimitrov

You could try the jQuery Globalization pluginfrom Microsoft:

你可以试试微软的jQuery Globalization 插件

<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>

<script src="@Url.Content("~/Scripts/jquery.glob.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/globinfo/jquery.glob.da-dk.js")" type="text/javascript"></script>
<script type="text/javascript">
    $.validator.methods.number = function (value, element) {
        return !isNaN($.parseFloat(value));
    }

    $(function () {
        $.preferCulture('da-DK');
    });
</script>


Plugin was renamed and moved, you should use Globalize(Mar 2012)

插件已重命名和移动,您应该使用Globalize(2012 年 3 月)

<script src="@Url.Content("~/Scripts/jquery.globalize/globalize.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.globalize/cultures/globalize.culture.da-DK.js")" type="text/javascript"></script>
<script type="text/javascript">
    $.validator.methods.number = function (value, element) {
        return !isNaN(Globalize.parseFloat(value));
    }

    $(document).ready(function () {
        Globalize.culture('da-DK');
    });
</script>

more about this on Scott Hanselman blog post

更多关于这个的Scott Hanselman 博客文章



回答by shatl

Updated script for current version of https://github.com/jquery/globalizewith optional elements support

更新了当前版本的https://github.com/jquery/globalize脚本,支持可选元素

$.validator.methods.number = function (value, element) {
   return this.optional(element) || !isNaN(Globalize.parseFloat(value));
}

$(function () {
    Globalize.culture('%%culture%%');
});

回答by RickAndMSFT

@shatl has the right answer as of today. Note for the range attribute you'll need a hack shown below. The complete code to add is shown below:

截至今天,@shatl 的答案是正确的。注意 range 属性,你需要一个如下所示的 hack。要添加的完整代码如下所示:

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    <script type="text/javascript" src="~/Scripts/globalize.js"></script>
    <script type="text/javascript" src="~/Scripts/globalize.culture.fr-FR.js"></script>
    <script type="text/javascript">
        $.validator.methods.number = function (value, element) {
            return this.optional(element) ||
                !isNaN(Globalize.parseFloat(value));
        }
        $(document).ready(function () {
            Globalize.culture('fr-FR');
        });

        jQuery.extend(jQuery.validator.methods, {    
            range: function (value, element, param) {        
                //Use the Globalization plugin to parse the value        
                var val = $.global.parseFloat(value);
                return this.optional(element) || (
                    val >= param[0] && val <= param[1]);
            }
        });
    </script>
}

回答by John Reilly

I ended up following the advice in Scott Hanselman's blog on this topic - you can read about this here:

我最终遵循了 Scott Hanselman 博客中关于这个主题的建议——你可以在这里阅读:

http://www.hanselman.com/blog/GlobalizationInternationalizationAndLocalizationInASPNETMVC3JavaScriptAndJQueryPart1.aspx

http://www.hanselman.com/blog/GlobalizationInternationalizationAndLocalizationInASPNETMVC3JavaScriptAndJQueryPart1.aspx

I had to make some changes to use Globalize instead of jQuery Global (now jQuery Global is dead). I wrote this up in the following blog post in case that's helpful:

我不得不进行一些更改以使用 Globalize 而不是 jQuery Global(现在 jQuery Global 已经死了)。我在下面的博客文章中写了这个,以防万一:

http://icanmakethiswork.blogspot.co.uk/2012/09/globalize-and-jquery-validate.html

http://icanmakethiswork.blogspot.co.uk/2012/09/globalize-and-jquery-validate.html

回答by Johnny

Just for future reference, what worked for me was the following:

仅供将来参考,对我有用的是以下内容:

Remember to set the proper jQuery version, and the correct culture, which in this example is danish.
If there can be no periods in the value then uncomment the comment.

请记住设置正确的 jQuery 版本和正确的文化,在这个例子中是丹麦语。
如果值中没有句点,则取消注释注释。

<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")"
    type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
    type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
    type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.globalize/globalize.js")"
    type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.globalize/cultures/globalize.culture.da-DK.js")"
    type="text/javascript"></script>
<script type="text/javascript">
        $.validator.methods.number = function (value, element) {
            // if (value.indexOf(".") >= 0) {
            //     return false;
            // }
            return (Globalize.parseFloat(value));
        }

        $(document).ready(function () {
            Globalize.culture('da-DK');
        });

        jQuery.extend(jQuery.validator.methods, {
            range: function (value, element, param) {
                //Use the Globalization plugin to parse the value
                var val = Globalize.parseFloat(value);
                return this.optional(element) || (val >= param[0] && val <= param[1]);
            }
        });
</script>

回答by Yogurtu

i'm from argentina, and i'm fighting with this problem a long time ago, we use "," as decimal separator, if you write "comma" javascript validation fails, but if you put ".", model will receibe a number translated to integer (55.60 will be 5560)

我来自阿根廷,很久以前我就在与这个问题作斗争,我们使用“,”作为小数点分隔符,如果你写“逗号”javascript验证失败,但如果你输入“。”,模型将收到一个数字转换为整数(55.60 将是 5560)

I solved out this problem with this simply solution:

我用这个简单的解决方案解决了这个问题:

1st-I upgraded jquery validation librarys, using new cdn addresses from: http://jqueryvalidation.org/

1st-我升级了 jquery 验证库,使用来自以下地址的新 cdn 地址:http: //jqueryvalidation.org/

the links that I included on my javascript are this:

我在我的 javascript 中包含的链接是这样的:

<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/jquery.validate.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/jquery.validate.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/additional-methods.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/additional-methods.min.js"></script>

and if you want it in a specific language (in my case Spanish) add this line too:

如果您想要特定语言(在我的情况下是西班牙语),也请添加以下行:

<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/localization/messages_es.js"></script>

Replace ES with the language you want.

用你想要的语言替换 ES。

2nd-If you want to allow numeric keypad decimal, you must replace "." with "," to work properly, add this code to your page to do that automatically:

2nd-如果你想允许数字键盘十进制,你必须替换“。” 使用“,”正常工作,将此代码添加到您的页面以自动执行此操作:

$('#txtCurrency').keyup(function () {

    $('#txtCurrency').val($('#txtCurrency').val().replace(/\./g, ','));

});


Presto, problem solved.

很快,问题解决了。

Bye.

再见。

回答by fabriciorissetto

No plugins

没有插件

I think the easiest way to workaround this without any pluginis by just overriding the default validation, like this:

我认为在没有任何插件的情况下解决此问题的最简单方法是覆盖默认验证,如下所示:

<script type="text/javascript">
    $.validator.methods.number = function (value, element) {            
        var regex = /^(\d*)(\,\d{1,2})?$/; //99999,99
        return regex.test(value);
    }
</script>

If you look at the source code of jquery.validate.jsyou will see that it just tests a regex like the code above, plus it validates if the element is optional:

如果您查看源代码,jquery.validate.js您会发现它只是像上面的代码一样测试正则表达式,此外它还验证元素是否为可选:

enter image description here

在此处输入图片说明

回答by Anders

Thanks for this page, saved me alot of trouble, I had to fix the globalize code how ever. Swedish culture does not accept dot as seperator, but since parseFloat uses the underlying javasacript parse dots will be accepcted as decimal seperator, but server side these will be rejected. To fix this i override the parseFloat like this

感谢这个页面,为我省去了很多麻烦,我不得不修复全球化代码。瑞典文化不接受点作为分隔符,但由于 parseFloat 使用底层 javasacript 解析点将被接受为十进制分隔符,但服务器端这些将被拒绝。为了解决这个问题,我像这样覆盖了 parseFloat

Globalize.orgParaseFloat = Globalize.parseFloat;
Globalize.parseFloat = function(value) {
    var culture = this.findClosestCulture();
    var seperatorFound = false;
    for (var i in culture.numberFormat) {
        if (culture.numberFormat[i] == ".") {
            seperatorFound = true;
        }
    }

    if (!seperatorFound) {
        value = value.replace(".", "NaN");
    }

    return this.orgParaseFloat(value);
};

I've open a ticket at their Github so maybe this will be fixed

我已经在他们的 Github 上开了一张票,所以也许这会被修复

回答by gsscoder

after some research... I found a solution.

经过一些研究......我找到了一个解决方案。

Web.configin <system.web>add

Web.config文件<system.web>添加

<globalization culture="auto" uiCulture="auto" enableClientBasedCulture="true"/>

Extend HtmlHelper class

扩展 HtmlHelper 类

namespace System.Web.Mvc
{
    public static class LocalizationHelper
    {
        public static IHtmlString MetaAcceptLanguage(this HtmlHelper html)
        {
            var acceptLang = HttpUtility.HtmlAttributeEncode(Thread.CurrentThread.CurrentUICulture.ToString());
            return new HtmlString(string.Format("<meta name=\"accept-language\" content=\"{0}\"/>", acceptLang));
        }
    }
}

_Layout.cshtmlat the end of <head>add

_Layout.cshtml在末尾<head>添加

@Html.MetaAcceptLanguage();
<script type="text/javascript">
    $(document).ready(function () {
        var data = $("meta[name='accept-language']").attr("content");
        $.global.preferCulture(data);
    });
</script>

After these changes I'm able to manipulate decimal numbers with my web gui.

在这些更改之后,我可以使用我的 web gui 操作十进制数字。

Regards, Giacomo

问候, 贾科莫