Open In App

How to limit the length of a string in AngularJS ?

Validation of fields is an important process while developing a dynamic web application. In various aspects of security, the validation is quite important. Along with this, the restriction of the limit to the length of a string is also an important process that helps to include the constraint for the maximum length for an input field or a text area. Limiting the length of a string can help to maintain a positive user experience by preventing the users from unintentionally entering long text which causes the issues of data corruption and all. In this article, we will see the approaches to limit the length of a string in AngularJS.

Approaches for limiting the length of a string

Steps to configure the AngularJS Application

The below steps will be followed to configure the AngularJS Application:



Step 1: Create a new folder for the project. We are using the VSCode IDE to execute the command in the integrated terminal of VSCode.

mkdir string-limit
cd string-limit

Step 2: Create the index.html file which will have the entire behavior of the application including the styling, AngularJS code, and structural HTML code.



We will understand the above concept with the help of suitable approaches & will understand its implementation through the illustration.

Limiting the length of a String Using built-in ‘limitTo’ Filter

In this approach, we are using the built-in filter names as the limitTo‘ filter which is responsible for limiting the user input to a maximum of 10 characters or the value that we want. The limitTo filter is used to limit the length of the string or the array type by actually slicing it to the specific maximum number of elements and allowing us to control the output length by adjusting the limit value. Here, we are allowing only 10 characters as the threshold limit, when the user crosses this limit, a warning popup is been displayed to the user specifying the message as Character Limit Exceeded.

Example: Below is an example that showcases the limiting length of a string in AngularJS using the limitTo filter.




<!doctype html>
<html ng-app="myApp">
  
<head>
    <script src=
    </script>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f0f0f0;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
        }
  
        .container {
            width: 100%;
            max-width: 400px;
            padding: 20px;
            background-color: #fff;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
        }
  
        .header {
            color: #228b22;
            text-align: center;
            font-size: 20px;
            font-weight: bold;
            margin-bottom: 20px;
        }
  
        .sub-header {
            font-size: 20px;
            color: rgb(0, 0, 0);
            margin-top: 10px;
            text-align: center;
        }
  
        .input-container {
            margin-top: 20px;
        }
  
        .input-container label {
            font-size: 18px;
            margin-bottom: 5px;
            color: #333;
        }
  
        .input-container input[type="text"] {
            width: 90%;
            padding: 10px;
            font-size: 16px;
            border: 1px solid rgb(255, 0, 0);
            border-radius: 4px;
        }
  
        .char-count {
            color: rgb(0, 0, 0);
            font-size: 16px;
            margin-top: 5px;
        }
  
        .char-limit {
            color: #777;
            font-size: 14px;
            text-align: center;
        }
  
        .char-limit-exceeded {
            color: red;
            font-size: 14px;
            text-align: center;
        }
  
        .truncated-text {
            color: blue;
            font-weight: bold;
            text-overflow: ellipsis;
            white-space: nowrap;
            overflow: hidden;
            max-width: 100%;
            font-size: 18px;
            margin-top: 20px;
            text-align: center;
        }
    </style>
</head>
  
<body ng-controller="myCtrl">
    <div class="container">
        <div class="header">
            <h1>GeeksforGeeks</h1>
        </div>
        <div class="sub-header">
            Approach 1: Using built-in `limitTo` Filter
        </div>
        <div class="input-container">
            <label for="inputText">Enter a text:</label>
            <input type="text"
                   id="inputText" 
                   ng-model="inputText" 
                   ng-change="charCountFunction()"
                placeholder="Max 10 characters" />
            <p class="char-count">
                  Character Count: {{ inputText.length }}
              </p>
            <p class="char-limit-exceeded" 
               ng-show="inputText.length > 10">
                Character limit exceeded!
            </p>
        </div>
        <div>
            <p class="truncated-text">
                  {{ inputText | limitTo: 10 }}
              </p>
        </div>
    </div>
    <script>
        var app = angular.module("myApp", []);
        app.controller("myCtrl", function ($scope) {
            $scope.inputText = "";
            $scope.charCountFunction = function () {
                if ($scope.inputText.length > 10) {
                    alert("Character limit exceeded!");
                    $scope.inputText = 
                          $scope.inputText.substr(0, 10);
                }
            };
        });
    </script>
</body>
  
</html>

Output:

Limiting the length of a String using Custom Directive

In this approach, we are using the custom directive to limit the length of the string in AngularJS. Here, we have used the custom directive called ‘charLimit” to mainly restrict the user input to a maximum of 20 characters allowed while typing. This defined directive tracks the the input changes and also truncates the input value if the exceeds the set threshold value of 20 characters. This also gives the alert message when the limit of charters is been crossed.

Example: Below is an example that showcases the limiting length of a string in AngularJS using Custom Directive.




<!doctype html>
<html ng-app="myApp">
  
<head>
    <script src=
    </script>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f0f0f0;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
        }
  
        .container {
            width: 100%;
            max-width: 400px;
            padding: 20px;
            background-color: #fff;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
        }
  
        .header {
            color: #4caf50;
            text-align: center;
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 20px;
        }
  
        .sub-header {
            font-size: 16px;
            color: rgb(0, 0, 0);
            text-align: center;
            margin-bottom: 10px;
        }
  
        .input-container {
            margin-top: 20px;
        }
  
        .input-container label {
            font-size: 18px;
            margin-bottom: 5px;
            color: rgb(0, 0, 0);
        }
  
        .input-container input[type="text"] {
            width: 90%;
            padding: 10px;
            font-size: 16px;
            border: 2px solid #ccc;
            border-radius: 4px;
        }
  
        .char-limit-exceeded {
            color: red;
            font-size: 14px;
            text-align: center;
            margin-top: 5px;
        }
    </style>
</head>
  
<body ng-controller="myCtrl">
    <div class="container">
        <div class="header">
            <h1>GeeksforGeeks</h1>
        </div>
        <div class="sub-header">
            <p>Approach 2: Using Custom Directive</p>
            <p>Maximum character limit is 20.</p>
        </div>
        <div class="input-container">
            <label for="inputText">
                  Enter a text:
              </label>
            <input type="text"
                   id="inputText" 
                   ng-model="inputText" 
                   char-limit="20" />
            <p class="char-limit-exceeded" 
               ng-show="inputText.length > 20">
                Character limit exceeded!
              </p>
        </div>
    </div>
    <script>
        var app = angular.module("myApp", []);
        app.controller("myCtrl", function ($scope) {
            $scope.inputText = "";
        });
        app.directive("charLimit", function () {
            return {
                restrict: "A",
                scope: {
                    charLimit: "=",
                },
                link: function (scope, element, attrs) {
                    element.on("input", function () {
                        var value = element.val();
                        if (value.length > scope.charLimit) {
                            scope.$apply(function () {
                                element.val(value.substr(0, scope.charLimit));
                            });
                        }
                    });
                },
            };
        });
    </script>
</body>
  
</html>

Output:


Article Tags :