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

Asked

Viewed 28,831 times

8

I have a problem with a variable of the type integer, for the maxlength="" only works with string and I need to stop, but it’s like Number. I think you need javascript, if anyone knows the solution would appreciate.

Observing: Already validated in backend.

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

  • You can do with Jquery.

  • if it is typed more than it should, the form will not give Submit... it is not enough?

  • 2

    for me it is, but will tell this to the analyst

  • Calm down, young man. It’ll get worse.

6 answers

7

By definition of HTML the element input with type="number" the property maxlength is ignored. as you can see in 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 attribute value type for text, email, search, password, tel, or url, this attribute specifies the maximum number of numeric characters (in Unicode) that the user can enter. To others type, he 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 that can be done 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>

<input id="field" type="text" maxlength="3" pattern="([0-9]{3})"/>

6

hello I have this code only accepts numbers and goes up to 3 look there.

$(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>
<input id="id_lock" name="id_lock" placeholder="Digite aqui" class="  verifica_numerico " required="" type="text" maxlength="3" size="4">

  • I will now test

  • all the codes I used that contain keycode is not right :/

  • opa, Uilherme possibly you are with conflict of many Pis on the same page, remember can only call once the jquery.js if not the pane why it gets lost. If you notice you can run my example and it works perfectly =D

4

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

For validation in I like 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);">

  • It would, however has the possibility of a funny user changing the type of input by inspecting elements, this only complicates a little more the life of the user, but still he can change the script, so the ideal is to create the validation in the backend

  • I flew when it comes to "change the type of input by inspecting elements," I think I’ll ask you this question, hehehe

  • see: https://media.giphy.com/media/3ohzdWpyfHizb4Jhew/giphy.gif

  • is already validated, and more for the sake of visual.

  • @Guilhermeoliveira edits your question and adds information about the code you tried, what to return on the console, and how your form

4

To limit an input from number-type for only 3 characters and the user can not continue typing beyond 3 characters this function meets.

NOTE: The HTML 5.2 specification explicitly allows the character 'and' 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 did another function (update 28/12/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>

  • I changed the answer to avoid entering with values type 00000010, 0000000998

  • it accepts only the letter 'and' :/

  • 1

    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.

  • I changed the answer to not accept sign - or sign +

  • If I type 999 and then use the default browser counter (firefox) I can get to 4 digits and probably more.

2

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

I made 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);
        }
    });
}

Use: in the first parameter will the input, in the form of a 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 in JS. It became a kind of "delay" when the number passes the limit and the function rewrites.

2

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

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 a EventListener in his input:

document.getElementById('meu-input').addEventListener('input', limitaTotal)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.