jQuery Javascript Regex 将文本字段限制为仅数字(必须允许不可打印的键)

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

Javascript Regex to limit Text Field to only Numbers (Must allow non-printable keys)

javascriptjqueryregexvalidationvalidationrules

提问by RMK

I have received PHP/JS code from previous developer and I need to add number validation to a Mobile Number field. I already have the HTML validation in place but I need to add that if someone presses an invalid key, that it doesn't get displayed only to highlight the field later in red because it contains invalid input.

我从以前的开发人员那里收到了 PHP/JS 代码,我需要向手机号码字段添加号码验证。我已经有了 HTML 验证,但我需要补充一点,如果有人按下无效键,它不会显示出来,只是为了稍后以红色突出显示该字段,因为它包含无效输入。

I've seen many regex's used and tried them but they had an either/or effect from what I need which is: If a letter or special character is entered, do not accept and do not display, all other input (digits, keys) is accepted (I need the invalid character not be displayed at all, not displayed and then erased). The regex that is working the most now is this:

我已经看到许多正则表达式的使用和尝试,但它们对我所需要的有一个/或一个效果:如果输入字母或特殊字符,不接受也不显示,所有其他输入(数字,键)被接受(我需要根本不显示无效字符,不显示然后删除)。现在最有效的正则表达式是这样的:

function filterNonDigits(evt)
{
  var event = evt || window.event;
  var keyentered = event.keyCode || event.which;
  keyentered = String.fromCharCode(keyentered);

  //var regex1 = /[0-9]|\./;
  var regex2 = /^[a-zA-Z.,;:|\\/~!@#$%^&*_-{}\[\]()`"'<>?\s]+$/;

  if( regex2.test(keyentered) ) {
    event.returnValue = false;
    if(event.preventDefault) event.preventDefault();
  }

When I used the commented regex1 (with the IF condition reversed), naturally it limited input to only digits thus preventing all keys such as Delete, BackSpace, etc. When using regex2, I still can't press Delete or the digits from the numpad.

当我使用注释的 regex1(与 IF 条件相反)时,它自然地将输入限制为仅数字,从而阻止所有键,例如 Delete、BackSpace 等。使用 regex2 时,我仍然无法按 Delete 或数字键盘中的数字.

So my question is, can the above code be modified to accept only digits but also allow keys? Another important point is that I need a method that doesn't use keycodes (8, 24 etc) for those key, in order to make sure all keyboard types can be used.

所以我的问题是,上面的代码可以修改为只接受数字但也允许密钥吗?另一个重要的一点是,我需要一种不使用这些键的键码(8、24 等)的方法,以确保可以使用所有键盘类型。



New Update:

新更新:

So my solution is as follows: If the "oninput" property exists, I use the solution provided by Ehtesham and if it doesn't, the backup uses the solution provided by Rohan Kumar. So it's something like this:

所以我的解决方案如下:如果“oninput”属性存在,我使用 Ehtesham 提供的解决方案,如果不存在,备份使用 Rohan Kumar 提供的解决方案。所以它是这样的:

if (obj.hasOwnProperty('oninput') || ('oninput' in obj)) 
{
    $('#mobileno').on('input', function (event) { 
        this.value = this.value.replace(/[^0-9]/g, '');
    });
} 
else 
{
    $('#mobileno').on('keypress',function(e){
        var deleteCode = 8;  var backspaceCode = 46;
        var key = e.which;
        if ((key>=48 && key<=57) || key === deleteCode || key === backspaceCode || (key>=37 &&  key<=40) || key===0)    
        {    
            character = String.fromCharCode(key);
            if( character != '.' && character != '%' && character != '&' && character != '(' && character != '\'' ) 
            { 
                return true; 
            }
            else { return false; }
         }
         else   { return false; }
    });
}

Thanks.

谢谢。

回答by Ehtesham

The best method here is to use inputevent which handles all your concerns. It is supported in all modern browsers. With jQuery you can do like following. Handles all cases pasting the value with mouse/keyboard backspace etc.

这里最好的方法是使用input处理您所有问题的事件。所有现代浏览器都支持它。使用 jQuery,您可以执行以下操作。处理使用鼠标/键盘退格键等粘贴值的所有情况。

$('.numeric').on('input', function (event) { 
    this.value = this.value.replace(/[^0-9]/g, '');
});

See it here

这里

You can check if inputevent is supported by checking if the input has this property if not you can use onkeyupfor older browsers.

您可以input通过检查输入是否具有此属性来检查事件是否受支持,如果没有,则可以onkeyup用于较旧的浏览器。

if (inputElement.hasOwnProperty('oninput')) {
    // bind input
} else {
    // bind onkeyup
}

回答by fred02138

A nice solution is described in a previous post:

一个很好的解决方案在描述以前的帖子

jQuery('.numbersOnly').keyup(function () { 
    this.value = this.value.replace(/[^0-9\.]/g,'');
});

回答by Rohan Kumar

Try it like,

试试看,

CSS

CSS

.error{border:1px solid #F00;}

SCRIPT

脚本

$('#key').on('keydown',function(e){
    var deleteKeyCode = 8;
    var backspaceKeyCode = 46;
    if ((e.which>=48 && e.which<=57) ||
         (e.which>=96 && e.which<=105)  || // for num pad numeric keys
         e.which === deleteKeyCode || // for delete key,
             e.which === backspaceKeyCode) // for backspace
         // you can add code for left,right arrow keys
    {
        $(this).removeClass('error');
        return true;
    }
    else
    {
        $(this).addClass('error');
        return false;
    }
});

Fiddle:http://jsfiddle.net/PueS2/

小提琴:http : //jsfiddle.net/PueS2/

回答by Stephan Muller

Instead of checking for the event keyCode, why don't you just check for changes inside the actual input and then filter out non-numbers?

与其检查事件 keyCode,不如只检查实际输入中的更改,然后过滤掉非数字?

This example uses keyup so that it can read what was actually entered, which means the character is briefly displayed and then removed, but hopefully you get my gist. It might even give the user feedback that the character is not allowed. Either way I think this is the easiest setup, let me know if you need more help fleshing this out.

此示例使用 keyup 以便它可以读取实际输入的内容,这意味着该字符会被短暂显示然后被删除,但希望您能理解我的要点。它甚至可能会向用户反馈不允许使用该字符。无论哪种方式,我都认为这是最简单的设置,如果您需要更多帮助来充实它,请告诉我。

function filterNonDigits(evt)
{
  var event = evt || window.event;
  var val = event.target.value;
  var filtered = val.replace(/[^0-9]/g, '');

    if(filtered !== val) {
      event.target.value = filtered;
      event.target.className += " error";
    }
}

http://jsfiddle.net/mEvSV/1/

http://jsfiddle.net/mEvSV/1/

(jquery used solely to easily bind the keyup function, you won't need it for your actual script)

(jquery 仅用于轻松绑定 keyup 函数,您的实际脚本不需要它)

回答by electricwizard

回答by Danimal Reks

This is a bit more concise...

这个比较简洁...

this.value = this.value.replace(/\D/gm, '');