AnaCS
AnaCS

Reputation: 1011

neither maxlenght or ng-maxlength seems to be working angularjs

I have the following input in my html file:

 <input name="password" 
        id="newPasswordConfirmation" 
        ng-model="newPasswordConfirmation" 
        type="number" 
        inputmode="numeric" 
        placeholder="" 
        required 
        minlength="8" 
        maxlength="8" 
        autocomplete="off" 
        ng-maxlength="8" 
        autocorrect="off" 
        autocapitalize="off" 
        style="-webkit-text-security: disc; text-security: disc;"> 

I want to limit the input to 8 algarisms, but when I type on my mobile device (android) , I can go on typing past 8 algarisms. Why is this not working and how can you make this restriction?

Upvotes: 1

Views: 1496

Answers (2)

Panteleimon.Kylish
Panteleimon.Kylish

Reputation: 185

Demo Fiddle

   <div ng-app="App" ng-controller="Ctrl">
       <input type="text"
           ng-model="model" 
           ng-keypress="limitKeypress($event, model, 8)"
           placeholder="enter first 8 digits">
    </div>

    angular.module('App', []).controller('Ctrl', Ctrl);

    function Ctrl($scope) {
        $scope.model = 'test'

        $scope.limitKeypress = function ($event, value, maxLength) {
            if (value != undefined && value.toString().length >= maxLength) {
                $event.preventDefault();
            }
        }

    }
    Ctrl.$inject = ['$scope'];

Upvotes: 0

davidkonrad
davidkonrad

Reputation: 85558

As mentioned in comments, maxlength does not work with number inputs. From MDN:

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 UTF-16 code units) that the user can enter. For other control types, it is ignored.

Here is a small directive you can use instead :

angular.module('myApp').directive('maxLength', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      var maxLength = attrs.maxLength || false;
      if (maxLength) element.on('keydown keypress keyup paste propertychange', function(e) {
        if (element[0].value.length >= maxLength - 1) {
          element[0].value = element[0].value.slice(0, maxLength)
        }
      })
    }
  }
});
<input type="number" max-length="8">

Upvotes: 1

Related Questions