Input of type NUMBER does not consider maxlength

3

I have the following HTML:

<input ng-model="idade" type="number" maxlength="3" placeholder="Informe a idade">

When I go to test, input ignores maxlength and lets me type as many characters as I want. Strangely, when I change the type to tel it works.

Has anyone ever gone through this and managed to solve ???

    
asked by anonymous 26.12.2016 / 13:55

3 answers

9

According to MDN documentation , you can only use maxlength to the text, email, search, password, tel, or url types.

This was a design decision.

If you wish, you can use min and max attributes to validate numbers. (remembering that this validation, by default, will be performed on the submit and not when typing).

    
26.12.2016 / 14:02
3

You can include a "mask" in the event keydown of input . Something like:

document.getElementById("numero").addEventListener('keydown', function(event) {

  if (this.value.length == 3 && event.keyCode != 8) {
    event.preventDefault();
    return false;
  }

});

function soNumeros(evt) {
  var theEvent = evt || window.event;
  var key = theEvent.keyCode || theEvent.which;
  key = String.fromCharCode( key );
  var regex = /[0-9]|\./;
  if (evt.keyCode)
    return true;
  if( !regex.test(key) ) {
    theEvent.returnValue = false;
    if(theEvent.preventDefault) theEvent.preventDefault();
  }
}
<input id="numero" ng-model="idade" type="number" maxlength="3" placeholder="Informe a idade" onkeypress='soNumeros(event)'>
    
26.12.2016 / 14:21
3

You can use Angular to create a directive :

var app = angular.module("app", []);

app.directive('ngMax', function() {
  return function(scope, element, attrs) {
    angular.element(element).on("keypress keydown", function(e) 
    { 
      if (e.keyCode != 8 && this.value.length == attrs.ngMax) 
      {  
         e.preventDefault();
         return false;
      }
    });
  };
});

app.controller("ctrl", ["$scope",
  function($scope) {

  }
]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>


<div ng-app="app" ng-controller="ctrl">
  <input ng-model="idade" 
         type="number"
         ng-maxlength="3" 
         ng-max="3" />
</div>

directive ngMax that can be used with the maximum number of numbers setting has been created.

    
26.12.2016 / 14:26