How to limit an input of type Number to only 3 characters?

9

I'm having a problem with a variable of type integer , because maxlength="" works only with string and needs to be barred, but it's type Number . I think you need the javascript, if anyone knows the solution would appreciate it.

Note: is already validated in the backend.

Update : I'm already using max="999" and min="0" , but only one message appears. The user can continue typing.

    
asked by anonymous 23.03.2017 / 15:07

6 answers

6

By HTML definition, the input element with type="number" the maxlength property is ignored. as you can check out in the MDN documentation

  

maxlength
  If the value of the type attribute is text, email, search, password,   tel, or url, this attribute specifies the maximum number of characters   (in Unicode code points) that the user can enter. For other control   types, it is ignored

Translating, if the value of the type attribute is text, email, search, password, tel, or url, this attribute specifies the maximum numeric characters (in Unicode) that the user can enter. For other type , it is ignored.

Remembering that you can justify to the analyst that the form will not be submitted if the number has not been typed correctly.

One way you can do this is by using jQuery and type="text" :

$(document).ready(function() {
  $("#field").keyup(function() {
      $("#field").val(this.value.match(/[0-9]*/));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputid="field" type="text" maxlength="3" pattern="([0-9]{3})"/>
    
23.03.2017 / 16:05
6

Hello, I have this code that only accepts numbers and goes up to 3 looks like that.

$(document).ready(function() {
  $(".verifica_numerico").keydown(function(e) {
    // Allow: backspace, delete, tab, escape, enter and .
    if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
      // Allow: Ctrl+A
      (e.keyCode == 65 && e.ctrlKey === true) ||
      // Allow: Ctrl+C
      (e.keyCode == 67 && e.ctrlKey === true) ||
      // Allow: Ctrl+X
      (e.keyCode == 88 && e.ctrlKey === true) ||
      // Allow: home, end, left, right
      (e.keyCode >= 35 && e.keyCode <= 39)) {
      // let it happen, don't do anything
      return;
    }
    // Ensure that it is a number and stop the keypress
    if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
      e.preventDefault();
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputid="id_lock" name="id_lock" placeholder="Digite aqui" class="  verifica_numerico " required="" type="text" maxlength="3" size="4">
    
23.03.2017 / 16:35
4

There are several ways to achieve the desired effect. But the ideal is to create a validation in the and if the input has somehow been passed with more than 3 characters, return an error.

For validation on the like of this solution, I find it very simple and clean:

function validar(field) {
  str = field.value;
  if (str.length > 2) {
    field.value = str.substring(0, str.length - 1);
  }
}

function numerico(evt) {
  var key_code = evt.keyCode ? evt.keyCode : evt.charCode ? evt.charCode : evt.which ? evt.which : void 0;
  if (key_code == 8 || key_code == 9 || key_code == 13 || key_code == 27 || key_code == 46) {
    return true;
  } else if ((key_code >= 35) && (key_code <= 40)) {
    return true
  } else if ((key_code >= 48) && (key_code <= 57)) {
    return true
  }
  return false;
}
<input type="text" onkeypress="validar(this); return numerico(event);">
    
23.03.2017 / 17:13
4
  

To limit a Number type input to only 3 characters and the user can not continue typing more than 3 characters, this function answers.

NOTE: The HTML 5.2 specification explicitly allows the 'e' character as part of a floating point number in exponential notation such as 1.23e-10.

  

But as with only 3 characters it would be impossible to use exponential notation I made another function (update 12/28/2018)

function somenteNumeros(e) {
    var charCode = e.charCode ? e.charCode : e.keyCode;
    // charCode 8 = backspace   
    // charCode 9 = tab
   if (charCode != 8 && charCode != 9) {
       // charCode 48 equivale a 0   
       // charCode 57 equivale a 9
       var max = 3;
       var num = document.getElementById('num');           
            
       if ((charCode < 48 || charCode > 57)||(num.value.length >= max)) {
          return false;
       }
       
    }
}
<input id="num" placeholder="Digite o numero" type="number" onkeypress="return somenteNumeros(event)" required>
    
23.03.2017 / 17:35
2

Well, I tested the maxlength here and it did not work, not the way I expected it to. (I thought it would block typing)

I've done a js function to limit the number of characters:

function limitar(el, limit){
    var el = document.querySelector(el);
    el.addEventListener('keyup', function(event){
        var input = event.target;
        var toStr = String(input.value);
        if(input.value.length > 3){
            var novo = toStr.slice(0, limit);
            input.value = parseInt(novo);
        }
    });
}

Usage: In the first parameter goes the input, in the form of css selector, and in the second parameter, the character limit.

Example: limitar('#meuinput', 3);

I want to make it clear that I am no master at JS. It was a kind of "delay" when the number goes beyond the limit and the function rewrites.

    
23.03.2017 / 16:21
2

You could make use of the .substr() method. :

function limitaTotal (evt) {
    var input = evt.target;
    var value = input.value;

    if (value.length <= 3) {
        return;
    }

    input.value = input.value.substr(0, 3); 
}

And to call your code, just add EventListener to your input :

document.getElementById('meu-input').addEventListener('input', limitaTotal)
    
23.03.2017 / 17:31