Tag Archives: maxlength

AngularJS Input Max Length Directive

In case you need to set a max length to a model binded input, well check this directive:

'use strict';

angular
.module('APP')
.directive('uiMaxlength', function() {
    return {
        require: 'ngModel',
        link: function(scope, el, attrs, model) {
            var max_length = parseInt(attrs.uiMaxlength, 10);

            var input_value_parser = function(value) {
                if(value.length > max_length) {
                    value = value.substring(0, max_length);
                    model.$setViewValue(value);
                    model.$render();
                }

                return value;
            };

            model.$parsers.push(input_value_parser);
        }
    };
})

;

Usage:

<input ui-maxlength="10"
       type="text"
       name="input_name"
       ng-model="model_name" />

With some minor changes this directive can also be used for setting Min Length.