【问题标题】:Validate Number in Javascript not working in Firefox验证 Javascript 中的数字在 Firefox 中不起作用
【发布时间】:2014-07-09 02:42:49
【问题描述】:

当输入文本为 0 到 10 (0,1,2,3,4,5,6,7,8,9,10) 时,此验证返回 true。 退格在 Firefox 中不起作用,在 Google Chrome 中,Internet Explorer 运行良好。我尝试启用退格的字符,但问题仍然存在。 如何让它在 Firefox 中运行?

我有这个:

<script>
function compruebacampo(evt, campotexto)
{
    var charCodeOfZero = 48;
    var numberJustEntered = evt.charCode - charCodeOfZero;
    var fullString = campotexto.value + "" + numberJustEntered;

    var matchesOne = false;
    for (var i = 0; i <= 10; i++) {
        if (fullString == ("" + i)) 
            matchesOne = true;
    }

    if (!matchesOne)
        return false;
}
</script>


<input type="textbox" onkeypress="return compruebacampo(event,this)" >

任何帮助将不胜感激。

【问题讨论】:

  • "keypress 事件在按下某个键并且该键通常会产生一个字符值时触发" -- developer.mozilla.org/en-US/docs/Web/Events/keypress
  • 我知道人们会因为我在这么小的情况下使用它而对我大喊大叫,但它是如此简单和跨浏览器:你为什么不使用 jQuery 呢?
  • 好的,我记住了@elclanrs

标签: javascript validation firefox


【解决方案1】:

我打算编写一个使用浏览器特定案例的函数(通过navigator.userAgent),但我认为这太笨重和复杂了。我认为最简单的做法是将事件处理程序绑定到该特定输入并让它监听keyCodes(FireFox 中的keys)。这种方法还避免了内联 JavaScript,这绝对是一个加分项。

event.keyCode < 58 && event.keyCode > 47

对于非 FireFox 浏览器,这会捕获所有数字 (0-9)。

event.key > -1 && event.key < 10

在 FireFox 中,这将捕获所有数字 (0-9),因为上述操作将失败。

event.keyCode == 8 || event.keyCode == 0

捕获退格并允许它们通过。

HTML

<input type="text" id="numberInput">

JavaScript

document.getElementById("numberInput").onkeypress = function (event) {
    if (event.keyCode < 58 && event.keyCode > 47 || event.key > -1 && event.key < 10) {
        /* nothing */
    } else if (event.keyCode == 8 || event.keyCode == 0) {
        /* nothing */
    } else {
        event.preventDefault();
    }
}

我在 Safari、FireFox 和 Chrome 中进行了测试。它对我来说在这三个方面都有效。我相信你可以将这些布尔值重写为一个 if 块。

fiddle

【讨论】:

  • 感谢您的帮助,但我只需要 0,1,2,3,4,5,6,7,8,9,10 而不是所有数字。请提供任何想法
【解决方案2】:

试试这个只允许在字段中输入数字的替代方法:http://jsfiddle.net/6faHh/

function compruebacampo(e, campotexto) {
    if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
            return false;
    }
}

【讨论】:

  • 感谢您的帮助,但我正在寻找仅验证 0、1、2、3、4、5、6、7、8、9、10 而非所有数字。请提供任何建议
【解决方案3】:
 $('input').keypress(function (e) {    
 if ($(this).attr('id') == "txtBoxId") {
                        regex = new RegExp("^[0-9\b]+$");
                        var charString = String.fromCharCode(!e.charCode ? e.which : e.charCode);
                        if (regex.test(charString)) {
                            return true;
                        }
                        else {
                            e.preventDefault();
                            return false;
                        }
                    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多