Javascript 输入数字验证 - 限制只能输入数字或数字,整数和浮点数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/30287531/
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
Input number validation - Restrict to enter only numbers or digits, int & float both
提问by vinayakj
How to restrict the input field to enter only numbers/digits int and float both. Sometimes we need to allow both integer as well as float value for fields like amount, so in that case the validation is required. There are no of solutions available but they are of large size code. So need a short but effective code.
如何限制输入字段只输入数字/数字 int 和 float 两者。有时我们需要允许像数量这样的字段同时使用整数和浮点值,因此在这种情况下需要验证。没有可用的解决方案,但它们是大型代码。所以需要一个简短但有效的代码。
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />
回答by vinayakj
No need for the long code for number input restriction just try this code.
It also accepts valid int & float both values.
不需要数字输入限制的长代码,只需尝试此代码即可。
它还接受有效的 int 和 float 两个值。
Javascript Approach
Javascript 方法
onload =function(){ 
  var ele = document.querySelectorAll('.number-only')[0];
  ele.onkeypress = function(e) {
     if(isNaN(this.value+""+String.fromCharCode(e.charCode)))
        return false;
  }
  ele.onpaste = function(e){
     e.preventDefault();
  }
}<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />jQuery Approach
jQuery 方法
$(function(){
  $('.number-only').keypress(function(e) {
 if(isNaN(this.value+""+String.fromCharCode(e.charCode))) return false;
  })
  .on("cut copy paste",function(e){
 e.preventDefault();
  });
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />UPDATE
更新
The above answers are for most common use case - validating input as a number.
以上答案适用于最常见的用例 - 将输入验证为数字。
But as per comments, some wants to allow few special cases like negative numbers & showing the invalid keystrokes to user before removing it, so below is the code snippet for such special use cases.
但是根据评论,有些人希望允许一些特殊情况,例如负数并在删除之前向用户显示无效的击键,因此以下是此类特殊用例的代码片段。
$(function(){
      
  $('.number-only').keyup(function(e) {
        if(this.value!='-')
          while(isNaN(this.value))
            this.value = this.value.split('').reverse().join('').replace(/[\D]/i,'')
                                   .split('').reverse().join('');
    })
    .on("cut copy paste",function(e){
     e.preventDefault();
    });
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />回答by clickbait
One-liner solution #1:
单线解决方案#1:
Use <input type="number">with the stepattribute.
<input type="number">与step属性一起使用。
<input type="number" step="0.0001"> // The user can enter up to 4 decimal places.
<input type="number" step="any"> // Not supported in all browsers, but permits numbers of any decimal precision.
You can also use the minand/or maxattributes to set the minimum value and/or the maximum value.
您还可以使用min和/或max属性来设置最小值和/或最大值。
One-liner solution #2:
单线解决方案#2:
Use a regular text inputelement with a RegExp patternattribute.
使用input带有 RegExppattern属性的常规文本元素。
<input type="text" pattern="^-?([0-9]*\.?[0-9]+|[0-9]+\.?[0-9]*)$">
This RegExp accepts numbers beginning with a dot ( .) and/or a negative sign ( -).
此 RegExp 接受以点 ( .) 和/或负号 ( -)开头的数字。
回答by Guy Schalnat
First things first. I prefer showing the invalid keystrokes rather than preventing them. User Experience Stack Exchange seems to agree at the moment (see this question).
先说第一件事。我更喜欢显示无效的击键而不是阻止它们。用户体验 Stack Exchange 目前似乎同意(请参阅此问题)。
That said, not everyone agrees, so let's see what we can do.
也就是说,并不是每个人都同意,所以让我们看看我们能做些什么。
Second. This doesn't replace a validation step. There are certain valid keystroke combinations that are not valid numbers, but need to be permitted in order to enter valid numbers. For example, the user could type a decimal mark (full stop or comma, depending on the language they are using), and then leave the text box, and you don't have a valid number. The following strings are all starts of numbers, but not yet valid:
第二。这不会取代验证步骤。某些有效的按键组合不是有效数字,但需要被允许才能输入有效数字。例如,用户可以键入小数点(句号或逗号,取决于他们使用的语言),然后离开文本框,而您没有有效的数字。以下字符串都是数字开头,但尚未生效:
- .
- -.
- ,
- -,
- .
- -.
- ,
- -,
The first two are the start of .5 or -.5, while the last two are the same in the various languages that use a comma instead of a full stop for the decimal mark.
前两个是 .5 或 -.5 的开头,而后两个在使用逗号而不是小数点的句号的各种语言中是相同的。
This brings us to the (already rejected)
这将我们带到(已被拒绝)
<input type="number" step="any">Of course, you will have to include a JavaScript script to fix non-modern browsers, but those are available. In theory, these should also work correctly when the user works in a language that uses the comma instead of the full stop for the decimal mark. Even better, since users usually use only one browser, and since they will be used to how input number works in that browser, and since they will spend most of their time on other websites than yours, they may get confused if your website does not behave the same way they are used to.
当然,您必须包含一个 JavaScript 脚本来修复非现代浏览器,但这些都是可用的。理论上,当用户使用使用逗号而不是小数点句号的语言工作时,这些也应该正常工作。更好的是,由于用户通常只使用一个浏览器,而且他们会习惯于在该浏览器中输入数字的工作方式,而且由于他们将大部分时间花在其他网站上而不是你的网站上,如果你的网站没有,他们可能会感到困惑以他们习惯的方式行事。
But maybe you still want to make your own solution. If all else fails, I would go with a regular expression (yes, I know, I now have two problems). I don't believe in allowing spaces, so I limit it to a negative sign, digits, and one decimal mark (whichever they are using). For example:
但也许您仍然想制定自己的解决方案。如果一切都失败了,我会使用正则表达式(是的,我知道,我现在有两个问题)。我不相信允许空格,因此我将其限制为负号、数字和一个小数点(无论它们使用的是哪个)。例如:
$('.rational-number').on('keypress', function(e)
{
  if (e.charCode >= 32 && e.charCode < 127 && 
      !/^-?\d*[.,]?\d*$/.test(this.value + '' + String.fromCharCode(e.charCode)))
  {
    return false;
  }
})<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type-"text" class="rational-number">This ALMOST works. The only problem I now have is, it assumes any character you type goes at the end of the string. This is fine except for the '-' for negative numbers, which is only allowed at the beginning. So you can type -5.4, but if you type 5.4 and then hit the home key or left arrow back to the beginning, it won't let you make it negative.
这几乎有效。我现在唯一的问题是,它假设您键入的任何字符都位于字符串的末尾。这很好,除了负数的“-”,它只允许在开头。所以你可以输入-5.4,但是如果你输入5.4然后按home键或向左箭头回到开头,它不会让你把它变成负数。
It also won't deal with pasting. Paste is a complicated topic. I don't agree with rejecting all paste operations. I feel the best option here is to just let the user paste and let the validator pick up any invalid numbers.
它也不会处理粘贴。粘贴是一个复杂的话题。我不同意拒绝所有粘贴操作。我觉得这里最好的选择是让用户粘贴并让验证器选择任何无效数字。
回答by mts knn
You can add a patternattribute to the input field. If the input value doesn't match the pattern, you can style the input field and/or show an error message by using the css selector :invalid:
您可以pattern向输入字段添加属性。如果输入值与模式不匹配,您可以使用 css 选择器设置输入字段的样式和/或显示错误消息:invalid:
.error-msg {
  display: none; /* Hide by default */
}
.number-only:invalid {
  background: pink;
}
.number-only:invalid + .error-msg {
  display: inline;
}<input type='tel' class='number-only' pattern='[+\-]?\d*\.?\d+' />
<span class='error-msg'>Please enter a valid integer or float value.</span>Some notes:
一些注意事项:
- type='tel'makes mobile browsers open a number keyboard, but of course you can also set the type to- text.
- Browser support for the patterninput attribute: http://caniuse.com/#feat=input-pattern
- Browser support for the :invalidcss selector: http://caniuse.com/#feat=form-validation
- The pattern regex doesn't support exponential notation, e.g. 1.23e4.
- The pattern regex doesn't allow spaces – they are not valid in int and float notation, but allowing them might improve user experience.
- type='tel'使手机浏览器打开一个数字键盘,当然你也可以将类型设置为- text。
- 浏览器对pattern输入属性的支持:http: //caniuse.com/#feat=input-pattern
- 浏览器对:invalidcss 选择器的支持:http: //caniuse.com/#feat=form-validation
- 模式正则表达式不支持指数表示法,例如1.23e4.
- 模式正则表达式不允许空格 - 它们在 int 和 float 符号中无效,但允许它们可能会改善用户体验。
回答by sivaprakash
Call one jquery function in onkeypress of the textbox. In that function use the respective ascii code to restrict input.
在文本框的 onkeypress 中调用一个 jquery 函数。在该函数中,使用相应的 ascii 代码来限制输入。
回答by Rizwan Siddiquee
User can not enter Decimal value in js. Try using this code :
用户不能在 js 中输入十进制值。尝试使用此代码:
if(document.getElementById(id).value.indexOf('.') != -1){
    print "do not Enter decimal nuber";
}

