Javascript 将文本字段限制为仅数字的最佳方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3764821/
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-23 06:03:38  来源:igfitidea点击:

Best way to restrict a text field to numbers only?

javascripthtmltextboxnumberstextfield

提问by RobHardgood

I'm using the following Javascript to restrict a text field on my website to only accept numerical input, and no other letters or characters. The problem is, it REALLY rejects all other key inputs, like ctrl-Ato select the text, or even any other browser functions like ctrl-Tor ctrl-Wwhile the text box is selected. Does anyone know of a better script to only allow numerical input, but not block normal commands (that aren't being directly input into the field)? Thanks Here is the code I'm using now:

我正在使用以下 Javascript 来限制我网站上的文本字段只接受数字输入,而不接受其他字母或字符。问题是,它真的拒绝所有其他键输入,例如ctrl-A选择文本,甚至任何其他浏览器功能,例如ctrl-Tctrl-W在选择文本框时。有谁知道更好的脚本只允许数字输入,但不阻止正常命令(不是直接输入到字段中)?谢谢这是我现在使用的代码:

function numbersonly(e, decimal) 
{
    var key;
    var keychar;

    if (window.event) 
        key = window.event.keyCode;
    else if (e) 
        key = e.which;
    else 
        return true;

    keychar = String.fromCharCode(key);

    if ((key==null) || (key==0) || (key==8) ||  (key==9) || (key==13) || (key==27))
       return true;     
    else if ((("0123456789").indexOf(keychar) > -1))
       return true;
    else if (decimal && (keychar == "."))
       return true;        
    else
       return false;
}

Edit: None of the solutions provided have solved my problem of allowing commands like ctrl-Awhile the text box is selected. That was the whole point of my asking here, so I have gone back to using my original script. Oh well.

编辑:提供的解决方案都没有解决我允许命令的问题ctrl-A当文本框被选中时。这就是我在这里提问的全部意义,所以我又回到了使用我原来的脚本。那好吧。

回答by Robert

This is something I made another time for just numbers, it will allow all the formatters as well.

这是我再次为数字所做的事情,它也将允许所有格式化程序。

jQuery

jQuery

$('input').keypress(function(e) {
    var a = [];
    var k = e.which;

    for (i = 48; i < 58; i++)
        a.push(i);

    if (!(a.indexOf(k)>=0))
        e.preventDefault();
});?

Try it

尝试一下

http://jsfiddle.net/zpg8k/

http://jsfiddle.net/zpg8k/

As a note, you'll want to filter on submit/server side as well, for sake of pasting/context menu and browsers that don't support the paste event.

请注意,为了粘贴/上下文菜单和不支持粘贴事件的浏览器,您还需要在提交/服务器端进行过滤。

Edit to elaborate on multiple methods

编辑以详细说明多种方法

I see you're bouncing around the 'accepted' answer, so I'll clear something up. You can really use any of the methods listed here, they all work. What I'd personally do is use mine for live client side filtering, and then on submit and server side use RegEx as suggested by others. However, no client side by itself will be 100% effectiveas there is nothing stopping me from putting document.getElementById('theInput').value = 'Hey, letters.';in the console and bypassing any clientside verification (except for polling, but I could just cancel the setIntervalfrom the console as well). Use whichever client side solution you like, but be sure you implement something on submit and server side as well.

我看到你在“接受”的答案周围蹦蹦跳跳,所以我会澄清一些事情。你真的可以使用这里列出的任何方法,它们都有效。我个人会做的是使用我的实时客户端过滤,然后在提交和服务器端按照其他人的建议使用 RegEx。但是,没有任何客户端本身是 100% 有效的,因为没有什么能阻止我放入 document.getElementById('theInput').value = 'Hey, letters.';控制台并绕过任何客户端验证(轮询除外,但我也可以setInterval从控制台取消)。使用您喜欢的任何客户端解决方案,但请确保您也在提交和服务器端实现了一些东西。

Edit 2 - @Tim Down

编辑 2 - @Tim Down

Alright, per the comments I had to adjust two things I didn't think of. First, keypress instead of keydown, which has been updated, but the lack of indexOf in IE (seriously Microsoft!?) breaks the example above as well. Here's an alternative

好吧,根据评论我不得不调整两件我没有想到的事情。首先,keypress 而不是 keydown,它已经更新,但是 IE 中缺少 indexOf(认真的微软!?)也打破了上面的例子。这是一个替代方案

$('input').keypress(function(e) {
    var a = [];
    var k = e.which;

    for (i = 48; i < 58; i++)
        a.push(i);

    if (!($.inArray(k,a)>=0))
        e.preventDefault();
});?

New jsfiddle: http://jsfiddle.net/umNuB/

新的 jsfiddle:http: //jsfiddle.net/umNuB/

回答by Hamund

This works in IE, Chrome AND Firefox:

这适用于 IE、Chrome 和 Firefox:

<input type="text" onkeypress="return event.charCode === 0 || /\d/.test(String.fromCharCode(event.charCode));" />

回答by ialpert

     .keypress(function(e)
               {
                 var key_codes = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 0, 8];

                 if (!($.inArray(e.which, key_codes) >= 0)) {
                   e.preventDefault();
                 }
               });

You need Backspace and Delete keys too ;)

您也需要退格键和删除键;)

回答by dogbane

http://jsfiddle.net/PgHFp/

http://jsfiddle.net/PgHFp/

<html>
<head>
<title>Test</title>
<script language="javascript">
function checkInput(ob) {
  var invalidChars = /[^0-9]/gi
  if(invalidChars.test(ob.value)) {
            ob.value = ob.value.replace(invalidChars,"");
      }
}
</script>
</head>

<body>
    <input type="text" onkeyup="checkInput(this)"/>
</body>
</html>

回答by Randy the Dev

Just use regex to get rid of any non number characters whenever a key is pressed or the textbox loses focus.

每当按下键或文本框失去焦点时,只需使用正则表达式即可摆脱任何非数字字符。

var numInput;
window.onload = function () {   
    numInput = document.getElementById('numonly');
    numInput.onkeydown = numInput.onblur = numInput.onkeyup = function()
    {
        numInput.value = numInput.value.replace(/[^0-9]+/,"");
    }
}

回答by Tim Down

The only event that contains information about the character typed is keypress. Anything character-related you may infer from the keyCodeproperty of keydownor keyupevents is unreliable and dependent on a particular keyboard mapping. The following will prevent non-numeric keyboard input all major browsers by using the character obtained from the keypressevent. It won't prevent the user from pasting or dragging non-numeric text in.

包含有关键入的字符的信息的唯一事件是keypress。您可以从或events的keyCode属性推断出的任何与字符相关的内容都是不可靠的,并且依赖于特定的键盘映射。以下将通过使用从事件中获得的字符来防止所有主要浏览器的非数字键盘输入。它不会阻止用户粘贴或拖动非数字文本。keydownkeyupkeypress

var input = document.getElementById("your_input");

input.onkeypress = function(evt) {
    evt = evt || window.event;
    if (!evt.ctrlKey && !evt.metaKey && !evt.altKey) {
        var charCode = (typeof evt.which == "undefined") ? evt.keyCode : evt.which;
        if (charCode && !/\d/.test(String.fromCharCode(charCode))) {
            return false;
        }
    }
};

回答by nicooga

Maybe you are using bootstrap. If so, this may suffice:

也许您正在使用引导程序。如果是这样,这可能就足够了:

<input type="text" data-mask="9999999"> 

Input mask

输入掩码

回答by hugo der hungrige

I use this:

我用这个:

    oEl.keypress(function(ev)
    {
        var sKey = String.fromCharCode(ev.which);
        if (!sKey.match(/[0-9]/) || !sKey === "") 
            ev.preventDefault();            
    });

The advantage is, that every key which does not provide an input to the field is still allowed, so you don't have to worry about every single special key. Even combos like CTRL + R do still work.

优点是,仍然允许每个不提供字段输入的键,因此您不必担心每个特殊键。即使像 CTRL + R 这样的组合仍然有效。

EDITAs this is not working in Firefox I had to modify the function a little:

编辑因为这在 Firefox 中不起作用,所以我不得不稍微修改一下函数:

    oEl.keypress(function(ev)
    {
        var iKeyCode = ev.which || ev.keyCode;
        var aSpecialKeysForFirefox = [8, 9, 13, 27, 37, 38, 39, 40, 46];
        var sKey = String.fromCharCode(iKeyCode);
        if (sKey !== "" && $.inArray(iKeyCode, aSpecialKeysForFirefox ) < 0 && !sKey.match(/[0-9]/)) {
            ev.preventDefault();
        }
    });

ExplanationAll Browsers handle jquerys keypress event differently. To make it work in FF the $.inArray check is added. As firefoxs keypress-event doesn't trigger when combinations like strg+tab are used, but the others do, the key.match approach still adds a little value to the latter, as it enables those combinations.

说明所有浏览器都以不同的方式处理 jquery 按键事件。为了使其在 FF 中工作,添加了 $.inArray 检查。由于使用 strg+tab 等组合时,firefoxs keypress-event 不会触发,但其他组合会触发,因此 key.match 方法仍然为后者增加了一点价值,因为它启用了这些组合。

回答by IlludiumPu36

Add <script type="text/javascript" src="jquery.numeric.js"></script>then use

添加<script type="text/javascript" src="jquery.numeric.js"></script>然后使用

 $("element").numeric({ decimal: false, negative: false });

回答by Nirmal

The following code is something I use extensively. I found the script in a forum, but modified and expanded it to accommodate my needs:

以下代码是我广泛使用的代码。我在论坛中找到了该脚本,但对其进行了修改和扩展以满足我的需求:

<script type="text/javascript">
    // Restrict user input in a text field
    // create as many regular expressions here as you need:
    var digitsOnly = /[1234567890]/g;
    var integerOnly = /[0-9\.]/g;
    var alphaOnly = /[A-Za-z]/g;
    var usernameOnly = /[0-9A-Za-z\._-]/g;

    function restrictInput(myfield, e, restrictionType, checkdot){
        if (!e) var e = window.event
        if (e.keyCode) code = e.keyCode;
        else if (e.which) code = e.which;
        var character = String.fromCharCode(code);

        // if user pressed esc... remove focus from field...
        if (code==27) { this.blur(); return false; }

        // ignore if the user presses other keys
        // strange because code: 39 is the down key AND ' key...
        // and DEL also equals .
        if (!e.ctrlKey && code!=9 && code!=8 && code!=36 && code!=37 && code!=38 && (code!=39 || (code==39 && character=="'")) && code!=40) {
            if (character.match(restrictionType)) {
                if(checkdot == "checkdot"){
                    return !isNaN(myfield.value.toString() + character);
                } else {
                    return true;
                }
            } else {
                return false;
            }
        }
    }
</script>

Different usage methods would be:

不同的使用方法是:

<!-- To accept only alphabets -->
<input type="text" onkeypress="return restrictInput(this, event, alphaOnly);">
<!-- To accept only numbers without dot -->
<input type="text" onkeypress="return restrictInput(this, event, digitsOnly);">
<!-- To accept only numbers and dot -->
<input type="text" onkeypress="return restrictInput(this, event, integerOnly);">
<!-- To accept only numbers and only one dot -->
<input type="text" onkeypress="return restrictInput(this, event, integerOnly, 'checkdot');">
<!-- To accept only characters for a username field -->
<input type="text" onkeypress="return restrictInput(this, event, usernameOnly);">