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

一个人想着一个人 提交于 2019-11-29 07:19:45

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

See it here

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
}
fred02138

A nice solution is described in a previous post:

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

Try it like,

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/

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?

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.

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/

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!