¿Cómo puedo limitar posibles entradas en un elemento "number" HTML5?


Para el elemento <input type="number">, maxlength no funciona. ¿Cómo puedo restringir el maxlength para ese elemento number?

Author: Pekka 웃, 2011-12-02

22 answers

Y puede agregar un atributo max que especificará el número más alto posible que puede insertar

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

Si agrega un valor max y un valor min, puede especificar el rango de valores permitidos:

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

El anterior todavía no dejar que un usuario introduzca manualmente un valor fuera del rango especificado. En su lugar, se le mostrará una ventana emergente diciéndole que ingrese un valor dentro de este rango al enviar el formulario como se muestra en este captura de pantalla:

introduzca la descripción de la imagen aquí

 257
Author: Cyclonecode,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-16 07:35:21

Puede especificar los atributos min y max, que permitirán la entrada solo dentro de un rango específico.

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

Esto solo funciona para los botones de control spinner, sin embargo. Aunque el usuario puede ser capaz de escribir un número mayor que el permitido max, el formulario no se enviará.

Mensaje de validación de Chrome para números mayores que el máximo
Captura de pantalla tomada de Chrome 15

Usted puede usar el evento HTML5 oninput en JavaScript para limitar el número de caracteres:

myInput.oninput = function () {
    if (this.value.length > 4) {
        this.value = this.value.slice(0,4); 
    }
}
 90
Author: Andy E,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-11 01:06:28

Si está buscando una solución Mobile Web en la que desee que su usuario vea un teclado numérico en lugar de un teclado de texto completo. Utilice type = "tel". Funcionará con maxlength, lo que le ahorra la creación de javascript adicional.

Max y Min todavía permitirán al usuario escribir números en exceso de max y min, lo cual no es óptimo.

 73
Author: Duane,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-09 16:48:49

Puedes combinar todos estos de la siguiente manera:

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


Actualización:
Es posible que también desee evitar que se introduzcan caracteres no numéricos, porque object.length sería una cadena vacía para las entradas numéricas, y por lo tanto su longitud sería 0. Por lo tanto, la función maxLengthCheck no funcionará.

Solución:
Ver thiso this para ejemplos.

Demo - Ver la versión completa del código de aquí:
http://jsfiddle.net/DRSDavidSoft/zb4ft1qq/1/

Actualización 2: Aquí está el código de actualización: https://jsfiddle.net/DRSDavidSoft/zb4ft1qq/2 /

Actualización 3: Tenga en cuenta que permitir que se ingrese más de un punto decimal puede estropear el valor numérico.

 57
Author: DRS David Soft,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:47:29

Es muy sencillo, con un poco de javascript puedes simular un maxlength, échale un vistazo:

//maxlength="2"
<input type="number" onKeyDown="if(this.value.length==2) return false;" />
 18
Author: Maycow Moura,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-18 22:08:45

O si su valor máximo es, por ejemplo, 99 y mínimo 0, puede agregar esto al elemento de entrada (su valor será reescrito por su valor máximo, etc.)

<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">

Entonces (si lo desea), puede verificar si es realmente el número de entrada

 14
Author: Richard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-01 15:33:49

Se puede especificar como texto, pero añadir pettern, que solo coinciden con los números:

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

Funciona perfecto y también en el móvil ( probado en iOS 8 y Android ) aparece el teclado numérico.

 12
Author: Христо Панайотов,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-21 08:53:26

//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>

Si utiliza el evento "onkeypress", no obtendrá ninguna limitación de usuario como tal durante el desarrollo ( prueba unitaria). Y si tiene un requisito que no permite al usuario ingresar después de un límite particular, eche un vistazo a este código e inténtelo una vez.

 11
Author: Prasad Shinde,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-02 02:39:26

La respuesta de Maycow Moura fue un buen comienzo. Sin embargo, su solución significa que cuando ingresa el segundo dígito, toda la edición del campo se detiene. Por lo tanto, no puede cambiar los valores ni eliminar ningún carácter.

El siguiente código se detiene en 2, pero permite que la edición continúe;

//MaxLength 2
onKeyDown="if(this.value.length==2) this.value = this.value.slice(0, - 1);"
 6
Author: Tim Wright,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-24 19:55:09

Max length no funcionará con <input type="number" la mejor manera que conozco es usar oninput event para limitar la longitud máxima. Por favor, consulte el siguiente código para una implementación simple.

<input name="somename"
    oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
    type = "number"
    maxlength = "6"
 />
 6
Author: Neha Jain,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-08 08:32:24

Tuve este problema antes y lo resolví usando una combinación de tipo de número html5 y jQuery.

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

Script:

$("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;
        }
    }
});

No se si los eventos son un poco exagerados pero eso resolvió mi problema. JSfiddle

 5
Author: tiltdown,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-09 13:37:00

Como han dicho otros, min/max no es lo mismo que maxlength porque las personas aún podrían ingresar un flotador que sería más grande que la longitud máxima de cadena que pretendía. Para emular verdaderamente el atributo maxlength, puedes hacer algo como esto en un pellizco (esto es equivalente a maxlength="16"):

<input type="number" oninput="if(value.length>16)value=value.slice(0,16)">
 5
Author: thdoan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-21 02:59:18

Otra opción es simplemente agregar un receptor para cualquier cosa con el atributo maxlength y agregar el valor slice a eso. Suponiendo que el usuario no quiere usar una función dentro de cada evento relacionado con la entrada. Aquí hay un fragmento de código. Ignora el código CSS y HTML, el JavaScript es lo que importa.

// 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>
 5
Author: Brandon Buttars,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-29 22:50:36

Al igual que con type="number", se especifica una propiedad max en lugar de maxlength, que es el número máximo posible. Así que con 4 dígitos, max debe ser 9999, 5 dígitos 99999 y así sucesivamente.

También si desea asegurarse de que es un número positivo, puede establecer min="0", asegurando números positivos.

 3
Author: Jan Dragsbaek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-12-02 10:38:28

Puede probar esto también para la entrada numérica con restricción de longitud

<input type="tel" maxlength="3" />
 3
Author: shinobi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-19 10:04:57

Entrada HTML

 <input class="minutesInput" type="number" min="10" max="120" value="" />
[2]} jQuery
 $(".minutesInput").on('keyup keypress blur change', function(e) {

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

  });
 2
Author: Hector,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-28 23:21:29

Una forma sencilla de establecer la longitud máxima para las entradas de números es:

<input type="number" onkeypress="if(this.value.length>=4) { return false;}" oninput="if(this.value.length>=4) { this.value = this.value.slice(0,4); }" />
 2
Author: HexboY,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-15 08:57:01

Sé que ya hay una respuesta, pero si desea que su entrada se comporte exactamente como el atributo maxlength o lo más cerca posible, use el siguiente código:

(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();
 1
Author: Philll_t,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-19 22:13:12

Como me enteré de que no se puede utilizar cualquiera de onkeydown, onkeypress o eventos onkeyup para una solución completa que incluye navegadores móviles. Por cierto onkeypress está en desuso y ya no está presente en chrome / opera para Android (ver: Eventos de interfaz de usuario W3C Working Draft, 04 August 2016).

Descubrí una solución usando el evento oninput solamente. Es posible que tenga que hacer la comprobación de números adicionales según sea necesario, como signo negativo / positivo o separadores decimales y mil y similares, pero como un comience lo siguiente debería ser suficiente:

function checkMaxLength(event) {
	// Prepare to restore the previous value.
	if (this.oldValue === undefined) {
		this.oldValue = this.defaultValue;
	}

	if (this.value.length > this.maxLength) {
		// Set back to the previous value.
		this.value = oldVal;
	}
	else {
		// Store the previous value.
		this.oldValue = this.value;
		
		// Make additional checks for +/- or ./, etc.
		// Also consider to combine 'maxlength'
		// with 'min' and 'max' to prevent wrong submits.
	}
}

También recomendaría combinar maxlength con min y max para prevenir el mal presenta como se indicó anteriormente en varias ocasiones.

 1
Author: markus s,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-26 10:56:09

Los atributos más relevantes para usar serían min y max.

 0
Author: Marcel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-12-02 10:37:41

Ugh. Es como si alguien se hubiera rendido a mitad de camino de implementarlo y pensara que nadie lo notaría.

Por cualquier razón, las respuestas anteriores no utilizan los atributos min y max. Este jQuery lo termina:

    $('input[type="number"]').on('input change keyup paste', function () {
      if (this.min) this.value = Math.max(parseInt(this.min), parseInt(this.value));
      if (this.max) this.value = Math.min(parseInt(this.max), parseInt(this.value));
    });

Probablemente también funcionaría como una función con nombre "oninput" sin jQuery si su uno de esos tipos "jQuery-is-the-devil".

 0
Author: Michael Cole,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-14 02:17:31

Para quién está buscando una limitación global como yo:

$(document).on('keypress','input[type="number"][maxlength]', function(){
    return this.value.length < +this.attributes.maxlength.value;
});

Esto captura cada tecla en el documento, y lo filtra si la entrada es una entrada "número" y tiene un atributo maxlength. Luego permite que la tecla presionada cuando la longitud no alcanzó la longitud máxima. También funciona con entradas y modales añadidos dinámicamente, etc.

 0
Author: Taha Paksu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-30 08:07:27