AngularJS – ngMaxlength Directive

AngularJSWeb DevelopmentFront End Technology

The ngMaxlength Directive in AngularJS adds the maxlength validator to the ngModel. This directive is mostly used to control the text-based inputs but can also be applied for controlling the custom text-based controls.

This validator sets the maxlength error key if the value ngModel.$viewValue is longer than the integer value obtained by evaluating the Angular JS expression defined in the ngMaxlength attribute value.


<element ng-maxlength="expression">..content..</element>

Example − ngMaxlength Directive

Create a file "ngMaxlength.html" in your Angular project directory and copy-paste the following code snippet.

<!DOCTYPE html>
      <title>ngMaxlength Directive</title>

<script src=""></script>

   <body ng-app="app" style="text-align: center;">
      <h1 style="color: green;">
         Welcome to Tutorials Point
         AngularJS | ngMaxlength Directive

      <div ng-controller="demo">
         <form name="form">
            <label for="maxlength">Input the text maxlength: </label>
            <input type="number" ng-model="maxlength" id="maxlength" />
            <br />
            <label for="input">This input is restricted by the current maxlength: </label>
            <input type="text" ng-model="model" id="input" name="input" ng-maxlength="maxlength" /><br />
            <br />
            input valid? = <code>{{form.input.$valid}}</code><br />
            model = <code>{{model}}</code>

         angular.module("app", []).controller("demo", [
            function ($scope) {
               $scope.maxlength = 5;


To run the above code, just go to your file and run it as a normal HTML file.

Observe the output when the length of the entered text becomes greater than the maxlength, the input becomes invalid.

Updated on 08-Oct-2021 12:31:32