JavaScript 只允许数字、逗号、点、退格

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

JavaScript to allow only numbers, comma, dot, backspace

javascriptregex

提问by vishnu reddy

i wrote a javascript function to allow only numbers, comma, dot like this

我写了一个 javascript 函数来只允许像这样的数字、逗号、点

function isNumber(evt) {
              var theEvent = evt || window.event;
              var key = theEvent.keyCode || theEvent.which;
              key = String.fromCharCode(key);
              var regex = /^[0-9.,]+$/;
              if (!regex.test(key)) {
                  theEvent.returnValue = false;
                  if (theEvent.preventDefault) theEvent.preventDefault();
              }

}

but if i want to remove any number form text box.. backspace is not working. then i changed regex code as "var regex = /^[0-9.,BS]+$/;"

但如果我想删除任何数字形式的文本框..退格键不起作用。然后我将正则表达式代码更改为“ var regex = /^[0-9.,BS]+$/;

still i am not able to use backspace in textbox.even i cant use left and right keys on textbox is i am doing wrong? can anyone help... thanks. (when I used "BS" in regex instead of backspace its allowing "B","S" Characters in textbox..)

我仍然无法在文本框中使用退格键。即使我不能在文本框中使用左右键也是我做错了吗?任何人都可以帮助...谢谢。(当我在正则表达式中使用“BS”而不是退格时,它允许文本框中的“B”、“S”字符......)

回答by anubhava

Try this code:

试试这个代码:

function isNumber(evt) {
          var theEvent = evt || window.event;
          var key = theEvent.keyCode || theEvent.which;
          key = String.fromCharCode(key);
          if (key.length == 0) return;
          var regex = /^[0-9.,\b]+$/;
          if (!regex.test(key)) {
              theEvent.returnValue = false;
              if (theEvent.preventDefault) theEvent.preventDefault();
          }
}

回答by Hemang Gandhi

Try this code, I modified it and worked for me to allow and comma, dot and digits only.

试试这个代码,我修改了它并对我来说有效,只允许和逗号、点和数字。

function isNumber(evt) {
   var theEvent = evt || window.event;
   var key = theEvent.keyCode || theEvent.which;            
   var keyCode = key;
   key = String.fromCharCode(key);          
   if (key.length == 0) return;
   var regex = /^[0-9.,\b]+$/;            
   if(keyCode == 188 || keyCode == 190){
      return;
   }else{
      if (!regex.test(key)) {
         theEvent.returnValue = false;                
         if (theEvent.preventDefault) theEvent.preventDefault();
      }
    }    
 }