Javascript正则表达式将文本字段限制为仅限数字(必须允许不可打印的键) [英] Javascript Regex to limit Text Field to only Numbers (Must allow non-printable keys)

查看:134
本文介绍了Javascript正则表达式将文本字段限制为仅限数字(必须允许不可打印的键)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到了之前开发人员的PHP / JS代码,我需要在手机号码字段中添加号码验证。我已经有了HTML验证,但是我需要添加一个,如果有人按下了无效的密钥,它不会只显示以后用红色突出显示该字段,因为它包含无效的输入。

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.

我看过很多正则表达式并且尝试了它们,但是它们对我所需要的有任何影响,如果输入了字母或特殊字符,不接受也不显示,所有接受其他输入(数字,键)(我需要根本不显示无效字符,不显示然后删除)。正在运行最多的正则表达式是:

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();
  }

当我使用评论的regex1时(在IF条件反转的情况下,自然它只限制数字输入,从而阻止所有键,如Delete,BackSpace等。使用regex2时,我仍然无法按下删除或小键盘中的数字。

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.

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

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.

所以我的解决方案如下:如果存在oninput属性,我使用Ehtesham提供的解决方案,如果没有,则t他的备份使用了Rohan Kumar提供的解决方案。所以它是这样的:

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:

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; }
    });
}

谢谢。

推荐答案

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

The best method here is to use input event 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.

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

看到它这里

您可以检查输入是否支持输入事件如果不是这个属性,你可以使用 onkeyup 用于旧浏览器。

You can check if input event is supported by checking if the input has this property if not you can use onkeyup for older browsers.

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

这篇关于Javascript正则表达式将文本字段限制为仅限数字(必须允许不可打印的键)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆