Html 如何限制 HTML5“数字”元素中可能的输入?

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

How can I limit possible inputs in a HTML5 "number" element?

htmlinputnumbersmax

提问by Prasad

For <input type="number">element, maxlengthis not working. How can I restrict the maxlengthfor that number element?

对于<input type="number">元素,maxlength不起作用。如何限制该maxlength数字元素?

采纳答案by Cyclonecode

And you can add a maxattribute that will specify the highest possible number that you may insert

您可以添加一个max属性,该属性将指定您可以插入的最高数字

<input type="number" max="999" />

if you add both a maxand a minvalue you can specify the range of allowed values:

如果同时添加 amaxmin值,则可以指定允许值的范围:

<input type="number" min="1" max="999" />

The above will still notstop a user from manually entering a value outside of the specified range. Instead he will be displayed a popup telling him to enter a value within this range upon submitting the form as shown in this screenshot:

以上仍然不会阻止用户手动输入指定范围之外的值。相反,他将显示一个弹出窗口,告诉他在提交表单时输入此范围内的值,如下面的屏幕截图所示:

enter image description here

在此处输入图片说明

回答by Andy E

You can specify the minand maxattributes, which will allow input only within a specific range.

您可以指定minmax属性,这将只允许在特定范围内输入。

<!-- equivalent to maxlength=4 -->
<input type="number" min="-9999" max="9999">

This only works for the spinner control buttons, however. Although the user may be able to type a number greater than the allowed max, the form will not submit.

但是,这仅适用于微调器控制按钮。尽管用户可以输入大于允许的数字max,但表单不会提交。

Chrome's validation message for numbers greater than the max
Screenshot taken from Chrome 15

Chrome 对大于最大值的数字的验证消息
Chrome 15 截图

You canuse the HTML5 oninputevent in JavaScript to limit the number of characters:

可以oninput在 JavaScript 中使用 HTML5事件来限制字符数:

myInput.oninput = function () {
    if (this.value.length > 4) {
        this.value = this.value.slice(0,4); 
    }
}

回答by Duane

If you are looking for a Mobile Websolution in which you wish your user to see a number pad rather than a full text keyboard. Use type="tel". It will work with maxlength which saves you from creating extra javascript.

如果您正在寻找一种移动 Web解决方案,您希望您的用户在其中看到数字键盘而不是全文键盘。使用类型=“电话”。它将与 maxlength 一起使用,从而使您免于创建额外的 javascript。

Max and Min will still allow the user to Type in numbers in excess of max and min, which is not optimal.

Max 和 Min 仍然允许用户输入超过 max 和 min 的数字,这不是最佳的。

回答by David Refoua

You can combine all of these like this:

您可以像这样组合所有这些:

<input name="myinput_drs"
oninput="maxLengthCheck(this)"
type = "number"
maxlength = "3"
min = "1"
max = "999" />

<script>
  // This is an old version, for a more recent version look at
  // https://jsfiddle.net/DRSDavidSoft/zb4ft1qq/2/
  function maxLengthCheck(object)
  {
    if (object.value.length > object.maxLength)
      object.value = object.value.slice(0, object.maxLength)
  }
</script>


Update:
You might also want to prevent any non-numeric characters to be entered, because object.lengthwould be an empty string for the number inputs, and therefore its length would be 0. Thus the maxLengthCheckfunction won't work.


更新:
您可能还想防止输入任何非数字字符,因为object.length对于数字输入而言,它将是一个空字符串,因此其长度将为0. 因此该maxLengthCheck功能将不起作用。

Solution:
See thisor thisfor examples.

解决方案:
请参阅示例。

Demo- See the full version of the code here:
http://jsfiddle.net/DRSDavidSoft/zb4ft1qq/1/

演示- 在此处查看完整版本的代码:http:
//jsfiddle.net/DRSDavidSoft/zb4ft1qq/1/

Update 2:Here's the update code: https://jsfiddle.net/DRSDavidSoft/zb4ft1qq/2/

更新2:这里是更新代码:https: //jsfiddle.net/DRSDavidSoft/zb4ft1qq/2/

Update 3:Please note that allowing more than a decimal point to be entered can mess up with the numeral value.

更新 3:请注意,允许输入多个小数点可能会混淆数值。

回答by Maycow Moura

it's very simple, with some javascript you can simulate a maxlength, check it out:

很简单,用一些javascript你可以模拟一个maxlength,看看:

//maxlength="2"
<input type="number" onKeyDown="if(this.value.length==2) return false;" />

回答by Richard

Or if your max value is for example 99 and minimum 0, you can add this to input element (your value will be rewrited by your max value etc.)

或者,如果您的最大值是例如 99 和最小值 0,您可以将其添加到输入元素(您的值将被您的最大值等重写)

<input type="number" min="0" max="99" 
   onKeyUp="if(this.value>99){this.value='99';}else if(this.value<0){this.value='0';}"
id="yourid">

Then (if you want), you could check if is input really number

然后(如果你愿意),你可以检查输入的是否真的是数字

回答by Chris Panayotoff

You can specify it as text, but add pettern, that match numbers only:

您可以将其指定为文本,但添加仅匹配数字的 pettern:

<input type="text" pattern="\d*" maxlength="2">

It works perfect and also on mobile ( tested on iOS 8 and Android ) pops out the number keyboard.

它运行完美,并且在移动设备上(在 iOS 8 和 Android 上测试)弹出数字键盘。

回答by Prasad Shinde

//For Angular I have attached following snippet.
<div ng-app="">
  <form>
    Enter number: <input type="number" ng-model="number" onKeyPress="if(this.value.length==7) return false;" min="0">
  </form>
  <h1>You entered: {{number}}</h1>
</div>

If you use "onkeypress" event then you will not get any user limitations as such while developing ( unit test it). And if you have requirement that do not allow user to enter after particular limit, take a look of this code and try once.

如果您使用“onkeypress”事件,那么您在开发时不会受到任何用户限制(单元测试)。如果您有要求不允许用户在特定限制后进入,请查看此代码并尝试一次。

回答by Brandon Buttars

Another option is to just add a listener for anything with the maxlength attribute and add the slice value to that. Assuming the user doesn't want to use a function inside every event related to the input. Here's a code snippet. Ignore the CSS and HTML code, the JavaScript is what matters.

另一种选择是为具有 maxlength 属性的任何内容添加一个侦听器,并将切片值添加到其中。假设用户不想在与输入相关的每个事件中使用函数。这是一个代码片段。忽略 CSS 和 HTML 代码,JavaScript 才是最重要的。

// Reusable Function to Enforce MaxLength
function enforce_maxlength(event) {
  var t = event.target;
  if (t.hasAttribute('maxlength')) {
    t.value = t.value.slice(0, t.getAttribute('maxlength'));
  }
}

// Global Listener for anything with an maxlength attribute.
// I put the listener on the body, put it on whatever.
document.body.addEventListener('input', enforce_maxlength);
label { margin: 10px; font-size: 16px; display: block }
input { margin: 0 10px 10px; padding: 5px; font-size: 24px; width: 100px }
span { margin: 0 10px 10px; display: block; font-size: 12px; color: #666 }
<label for="test_input">Text Input</label>
<input id="test_input" type="text" maxlength="5"/>
<span>set to 5 maxlength</span>

<br>

<label for="test_input">Number Input</label>
<input id="test_input" type="number" min="0" max="99" maxlength="2"/>
<span>set to 2 maxlength, min 0 and max 99</span>

回答by Neha Jain

Max length will not work with <input type="number"the best way i know is to use oninputevent to limit the maxlength. Please see the below code for simple implementation.

最大长度不适用于<input type="number"我所知道的最好方法是使用oninput事件来限制最大长度。简单的实现请看下面的代码。

<input name="somename"
    oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
    type = "number"
    maxlength = "6"
 />