Search code examples
angularjsmaterial-designmd-autocomplete

Angular material design md-autocomplete with md-max-length and pattern


I'm using md-autocomplete directive as a address for zip code lookup. I want to limit what the user type in the control to five digit zip code only. It has to be numbers and limited to 5 numbers.

How can I achieve this in md-autocomplete?


Solution

  • you can achieve this with a filter: http://jsfiddle.net/uhmgp23h/2/

    <body ng-app="MyApp">
        <div ng-controller="MyController">
            <input type="text" ng-model="zip" />
        </div>
    </body>
    

    js

    var app = angular.module('MyApp',[]);
    app.controller('MyController', function($scope, $filter)
    {
        $scope.zip = '';
        $scope.$watch('zip', function(newVal, oldVal)
        {
            var value = String(newVal);   
            var number = value.replace(/[^0-9]+/g,'');
            $scope.zip = $filter('numberFixedLen')(number,5);
        });
    });
    
    app.filter('numberFixedLen', function()
    {
          return function(n, len)
          {
              var num = parseInt(n);
              if (String(num).length > len) return n.substring(0, len);
              return num;
          };
    });
    

    This filter will restrict the field to numbers only and also limit it to 5 characters. This filter will work with any number of chars, just change the 5 to whatever you want in this line $filter('numberFixedLen')(number,5);