Tag Archives: char limit

Maximum character length in angularJS

Restricting characters to specified length directive.

We want a input field to restrict some characters from user, only allowing specified number of characters into the field
for this i have written a directive that satisfies the above requirement.

Below we can see code snippet and understanding of the snippet.

Minimum Requirement to understand the code: Must know Directive in AngularJS.
Usage:
input name=”name” type=”number”


myMaxlength.directive('myMaxlength', ['$compile', '$log', function($compile, $log) {
  return {
     restrict: 'A',
     require: 'ngModel',
     link: function (scope, elem, attrs, ctrl) {
           attrs.$set("ngTrim", "false");
           var maxlength = parseInt(attrs.myMaxlength, 10);
           ctrl.$parsers.push(function (value) {
           $log.info("In parser function value = [" + value + "].");
             if (value.length > maxlength)
             {
                  $log.info("The value [" + value + "] is too long!");
                  value = value.substr(0, maxlength);
                  ctrl.$setViewValue(value);
                  ctrl.$render();
                  $log.info("The value is now truncated as [" + value + "].");
              }
              return value;
            });
        }
    };
}]);

In the above code snippet we have control(ctrl) has method $parsers which gets called as soon as the value in the form input (number) is modified by the user, each value is pushed to array of character and length of the array is checked with specified maxlength value, if the array of input is greater than the maxLength value then control(ctrl) does not render to view else will be $setViewValue is called and $render will render the input to the view element.