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

如何限制HTML5中可能的输入;“数字”;元素?,html,input,numbers,max,Html,Input,Numbers,Max,对于元素,maxlength不起作用。如何限制该数字元素的maxlength?您可以指定min和max属性,这将只允许在特定范围内输入 <!-- equivalent to maxlength=4 --> <input type="number" min="-9999" max="9999"> 要使用的更多相关属性是min和max与type=“number”一样,您可以指定一个max属性,而不是maxlength属性,后者是可能的最大数量。因此,对于4位数字,max应该

对于
元素,
maxlength
不起作用。如何限制该数字元素的
maxlength

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

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

要使用的更多相关属性是
min
max

type=“number”
一样,您可以指定一个
max
属性,而不是
maxlength
属性,后者是可能的最大数量。因此,对于4位数字,
max
应该是
9999
,5位
99999
,依此类推


另外,如果要确保它是正数,可以设置
min=“0”
,以确保正数。

并且可以添加一个
max
属性,该属性将指定可以插入的最大可能数字

<input type="number" max="999" />
上述操作仍将不会阻止用户手动输入超出指定范围的值。相反,他将显示一个弹出窗口,告诉他在提交表单时输入此范围内的值,如此屏幕截图所示:


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

<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>
    const [amount, setAmount] = useState("");
    
   return(
    <input onChange={(e) => {
    setAmount(e.target.value);
    if (e.target.value.length > 4) {
         setAmount(e.target.value.slice(0, 4));
    }
    }} value={amount}/>)

//这是一个旧版本,请查看更新的版本
// https://jsfiddle.net/DRSDavidSoft/zb4ft1qq/2/
函数maxLengthCheck(对象)
{
if(object.value.length>object.maxLength)
object.value=object.value.slice(0,object.maxLength)
}

更新:
您可能还希望防止输入任何非数字字符,因为
object.length
将是数字输入的空字符串,因此其长度将为
0
。因此,
maxLengthCheck
功能将无法工作

解决方案:
有关示例,请参见或

演示-在此处查看完整版本的代码:

更新2:以下是更新代码:

更新3:
请注意,允许输入超过一个小数点可能会弄乱数字值。

如果您正在寻找一种移动Web解决方案,希望用户看到的是数字键盘而不是全文键盘。使用type=“tel”。它将与maxlength一起工作,这样可以避免创建额外的javascript


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

这非常简单,使用一些javascript可以模拟一个
maxlength
,请查看:

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

Maycow Moura的回答是一个好的开始。 然而,他的解决方案意味着,当您输入第二位数字时,该字段的所有编辑都将停止。因此,您不能更改值或删除任何字符

以下代码在2处停止,但允许继续编辑

//MaxLength 2
onKeyDown="if(this.value.length==2) this.value = this.value.slice(0, - 1);"

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



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

您也可以对具有长度限制的数字输入尝试此操作

<input type="tel" maxlength="3" />

我以前遇到过这个问题,我结合使用html5数字类型和jQuery解决了这个问题

<input maxlength="2" min="0" max="59" name="minutes" value="0" type="number"/>

脚本:

$("input[name='minutes']").on('keyup keypress blur change', function(e) {
    //return false if not 0-9
    if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
       return false;
    }else{
        //limit length but allow backspace so that you can still delete the numbers.
        if( $(this).val().length >= parseInt($(this).attr('maxlength')) && (e.which != 8 && e.which != 0)){
            return false;
        }
    }
});
$(“输入[name='minutes'])。打开('keyup keypress blur change',函数(e){
//如果不是0-9,则返回false
如果(e.which!=8&&e.which!=0&&e.which<48 | e.which>57)){
返回false;
}否则{
//限制长度,但允许退格,以便仍然可以删除数字。
if($(this.val().length>=parseInt($(this.attr('maxlength'))&&(e.which!=8&&e.which!=0)){
返回false;
}
}
});
我不知道这些事件是否有点过分,但它解决了我的问题。

正如其他人所说,min/max与maxlength不同,因为人们仍然可以输入一个大于预期最大字符串长度的浮点值。要真正模拟maxlength属性,您可以在必要时执行类似操作(这相当于maxlength=“16”):


我知道已经有答案了,但如果您希望输入的行为与
maxlength
属性完全相同或尽可能接近,请使用以下代码:

(function($) {
 methods = {
    /*
     * addMax will take the applied element and add a javascript behavior
     * that will set the max length
     */
    addMax: function() {
        // set variables
        var
            maxlAttr = $(this).attr("maxlength"),
            maxAttR = $(this).attr("max"),
            x = 0,
            max = "";

        // If the element has maxlength apply the code.
        if (typeof maxlAttr !== typeof undefined && maxlAttr !== false) {

            // create a max equivelant
            if (typeof maxlAttr !== typeof undefined && maxlAttr !== false){
                while (x < maxlAttr) {
                    max += "9";
                    x++;
                }
              maxAttR = max;
            }

            // Permissible Keys that can be used while the input has reached maxlength
            var keys = [
                8, // backspace
                9, // tab
                13, // enter
                46, // delete
                37, 39, 38, 40 // arrow keys<^>v
            ]

            // Apply changes to element
            $(this)
                .attr("max", maxAttR) //add existing max or new max
                .keydown(function(event) {
                    // restrict key press on length reached unless key being used is in keys array or there is highlighted text
                    if ($(this).val().length == maxlAttr && $.inArray(event.which, keys) == -1 && methods.isTextSelected() == false) return false;
                });;
        }
    },
    /*
     * isTextSelected returns true if there is a selection on the page. 
     * This is so that if the user selects text and then presses a number
     * it will behave as normal by replacing the selection with the value
     * of the key pressed.
     */
    isTextSelected: function() {
       // set text variable
        text = "";
        if (window.getSelection) {
            text = window.getSelection().toString();
        } else if (document.selection && document.selection.type != "Control") {
            text = document.selection.createRange().text;
        }
        return (text.length > 0);
    }
};

$.maxlengthNumber = function(){
     // Get all number inputs that have maxlength
     methods.addMax.call($("input[type=number]"));
 }

})($)

// Apply it:
$.maxlengthNumber();
(函数($){
方法={
/*
*addMax将获取应用的元素并添加javascript行为
*这将设置最大长度
*/
addMax:function(){
//设置变量
变量
maxlAttr=$(this.attr(“maxlength”),
maxAttR=$(this.attr(“max”),
x=0,
max=“”;
//如果元素具有maxlength,则应用代码。
if(typeof maxlAttr!==typeof undefined&&maxlAttr!==false){
//创建一个最大等效线
if(typeof maxlAttr!==typeof undefined&&maxlAttr!==false){
while(x$("input[name='minutes']").on('keyup keypress blur change', function(e) {
    //return false if not 0-9
    if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
       return false;
    }else{
        //limit length but allow backspace so that you can still delete the numbers.
        if( $(this).val().length >= parseInt($(this).attr('maxlength')) && (e.which != 8 && e.which != 0)){
            return false;
        }
    }
});
<input type="number" oninput="if(value.length>16)value=value.slice(0,16)">
(function($) {
 methods = {
    /*
     * addMax will take the applied element and add a javascript behavior
     * that will set the max length
     */
    addMax: function() {
        // set variables
        var
            maxlAttr = $(this).attr("maxlength"),
            maxAttR = $(this).attr("max"),
            x = 0,
            max = "";

        // If the element has maxlength apply the code.
        if (typeof maxlAttr !== typeof undefined && maxlAttr !== false) {

            // create a max equivelant
            if (typeof maxlAttr !== typeof undefined && maxlAttr !== false){
                while (x < maxlAttr) {
                    max += "9";
                    x++;
                }
              maxAttR = max;
            }

            // Permissible Keys that can be used while the input has reached maxlength
            var keys = [
                8, // backspace
                9, // tab
                13, // enter
                46, // delete
                37, 39, 38, 40 // arrow keys<^>v
            ]

            // Apply changes to element
            $(this)
                .attr("max", maxAttR) //add existing max or new max
                .keydown(function(event) {
                    // restrict key press on length reached unless key being used is in keys array or there is highlighted text
                    if ($(this).val().length == maxlAttr && $.inArray(event.which, keys) == -1 && methods.isTextSelected() == false) return false;
                });;
        }
    },
    /*
     * isTextSelected returns true if there is a selection on the page. 
     * This is so that if the user selects text and then presses a number
     * it will behave as normal by replacing the selection with the value
     * of the key pressed.
     */
    isTextSelected: function() {
       // set text variable
        text = "";
        if (window.getSelection) {
            text = window.getSelection().toString();
        } else if (document.selection && document.selection.type != "Control") {
            text = document.selection.createRange().text;
        }
        return (text.length > 0);
    }
};

$.maxlengthNumber = function(){
     // Get all number inputs that have maxlength
     methods.addMax.call($("input[type=number]"));
 }

})($)

// Apply it:
$.maxlengthNumber();
<input type="text" pattern="\d*" maxlength="2">
<input name="somename"
    oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
    type = "number"
    maxlength = "6"
 />
 <input class="minutesInput" type="number" min="10" max="120" value="" />
 $(".minutesInput").on('keyup keypress blur change', function(e) {

    if($(this).val() > 120){
      $(this).val('120');
      return false;
    }

  });
    $('input[type="number"]').on('input change keyup paste', function () {
      if (this.min) this.value = Math.max(parseInt(this.min), parseInt(this.value) || 0);
      if (this.max) this.value = Math.min(parseInt(this.max), parseInt(this.value) || 0);
    });
<input type="number" onchange="this.value=Math.max(Math.min(this.value, 100), -100);" />
<input type="number" onchange="this.value=this.value ? Math.max(Math.min(this.value,100),-100) : null" />
<input type="number" min="0" max="1000" onkeyup="if(parseInt(this.value)>1000){ this.value =1000; return false; }">
$('input[type=datetime-local]').each(function( index ) {

    $(this).change(function() {
      var today = new Date();
      var date = new Date(this.value);
      var yearFuture = new Date();
      yearFuture.setFullYear(yearFuture.getFullYear()+100);

      if(date.getFullYear() > yearFuture.getFullYear()) {

        this.value = today.getFullYear() + this.value.slice(4);
      }
    })
  });
$(document).on('input', ':input[type="number"][maxlength]', function () {
    if (this.value.length > this.maxLength) {
        this.value = this.value.slice(0, this.maxLength); 
    }
});
<input id="maxLengthCheck" 
       name="maxLengthCheck" 
       type="number" 
       step="1" 
       min="0" 
       oninput="this.value = this.value > 5 ? 5 : Math.abs(this.value)" />
<input id="horaReserva" type="number" min="1" max="12" onkeypress="return isIntegerInput(event)" oninput="maxLengthCheck(this)">

function maxLengthCheck(object) {
    if (object.value.trim() == "") {

    }
    else if (parseInt(object.value) > parseInt(object.max)) {
        object.value = object.max ;
    }
    else if (parseInt(object.value) < parseInt(object.min)) {
        object.value = object.min ;
    }
}

function isIntegerInput (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();
        }
    }
}
    const [amount, setAmount] = useState("");
    
   return(
    <input onChange={(e) => {
    setAmount(e.target.value);
    if (e.target.value.length > 4) {
         setAmount(e.target.value.slice(0, 4));
    }
    }} value={amount}/>)