HTML5 - type =" number"防止Chrome中的非数字,但IE和& FF

时间:2015-11-17 13:45:40

标签: html5 forms google-chrome internet-explorer firefox

我在MVC中编写了一个网站,我的表单中有一个价格字段。 我的Razor代码如下所示:

@Html.EditorFor(model => model.Price, new { htmlAttributes = new { @class = "myclass", min = 0, max = 1000000 } })

我的ViewModel属性如下所示:

[Display(Name = "Price")]
[Range(0, 1000000, ErrorMessage="Please enter a valid Price")]
public int Price { get; set; }

在Chrome中,用户无法输入除.以外的任何其他字符,但可以在Firefox和Internet Explorer中输入,这不是我想要的。

HTML5标准没有扩展到UI是否正确? Chrome会做奖金吗?或IE和FF应该阻止字母(例如像$这样的字符)和我做错了什么?

编辑:如果我在IE中开始输入,比如$,它会在失去焦点时使控件空白。在Firefox中它仍然存在。

1 个答案:

答案 0 :(得分:0)

我通过使用JQuery解决了这个问题。这些是步骤:

1)创建要加载的外部文件 - MyUtils.js

2)粘贴在这个JQuery代码中:

// Use like: $('#SomeId').forceNumeric()
jQuery.fn.forceNumeric = function (intsOnly) {
    return this.each(function () {
      $(this).keydown(function (e) {
        var key = e.which || e.keyCode;
        if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
            // numbers   
            key >= 48 && key <= 57 ||
            // Numeric keypad
            key >= 96 && key <= 105 ||
            // Backspace and Tab and Enter
           key == 8 || key == 9 || key == 13 ||
            // Home and End
           key == 35 || key == 36 ||
            // left and right arrows
           key == 37 || key == 39 ||
            // Del and Ins
           key == 46 || key == 45)
        {
            // ints only: look for a decimal. Disallow comma
            // minus and period on keypad
                if ((intsOnly) && (key == 190 || key == 188 || key == 109 || key == 110)) {
                    return false;
            }
                // Input is OKAY
                return true;
            }
        return false;
         });
    });
}

3)在您要使用它的页面上,加载js文件     例如script src =&#34; /Scripts/MyUtils.js"

4)将方法应用于设置

上的字段
$('#Price').forceNumeric(true);