Open In App

How to limit the length of a string in AngularJS ?

Last Updated : 04 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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

  • Using built-in ‘limitTo’ Filter
  • Using Custom Directive

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.

HTML




<!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:

Str1

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.

HTML




<!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:

Str2



Similar Reads

How to Reset an Input Value when Limit Exceeds using AngularJS ?
The task is to handle an input field if the number entered by the user in the input exceeds some limit using angularJS. We define a limitTo directive and use it on an HTML input element. This directive is used for all the handling of overflowing limits. The directive calls a function on the keypress event where we can check for the limits. Example
2 min read
How to limit string length in PHP ?
A string is a sequence of characters in PHP. The length of the string can be limited in PHP using various in-built functions, wherein the string character count can be restricted. Approach 1 (Using for loop): The str_split() function can be used to convert the specified string into the array object. The array elements are individual characters stor
3 min read
Set the limit of text length to N lines using CSS
It is possible to limit the text length to [Tex]N[/Tex] lines using CSS. This is known as line clamping or multiple line truncating. There can be two possible cases: Truncating text after 1 line: If you need to truncate text after 1 line then the text-overflow property of CSS can be used. It creates ellipses and gracefully cut off words. div{ white
4 min read
Max Length of Subarray with Given Sum Limit in JavaScript Array
Given an array, our task is to find the maximum length of a subarray whose sum does not exceed a given value. We can use different approaches like the Brute Force Approach and the Sliding Window Approach to find the maximum length of a subarray. Below are the approaches to find the maximum length of a subarray with a sum not exceeding a given value
3 min read
How to replace a string by another string in AngularJS ?
In this article, we will see how to select a string from the text and replace it with another string using AngularJS and will understand it through the illustrations. The replace() method can be used to search the particular character(s), which is getting replaced with a specific character(s) &amp; return a new generated string. Syntax: string.repl
2 min read
How to display length of filtered ng-repeat data in AngularJS ?
The task is to Display the length of filtered ng-repeat data. Here we are going to use alias expression to solve this problem. Approach: To display the length of filtered ng-repeat data we use an alias expression. We create an alias for the variable used to filter the ng-repeat data and display the length of the alias at each moment. Syntax: &lt;el
2 min read
Mongoose Aggregate.prototype.limit() API
The Aggregate API.prototype.limit() function of the Mongoose API is used to limit the number of documents that get passed to the next stage in the aggregator pipeline. Syntax: Aggregate.prototype.limit() Parameters: It accepts a single parameter as described below: num: It is a number that defines the maximum number of documents that get passed to
2 min read
PHP | MySQL LIMIT Clause
In MySQL the LIMIT clause is used with the SELECT statement to restrict the number of rows in the result set. The Limit Clause accepts one or two arguments which are offset and count.The value of both the parameters can be zero or positive integers. Offset:It is used to specify the offset of the first row to be returned. Count:It is used to specify
3 min read
How to limit character input in textarea including count in jQuery ?
In this article, we will set the limit character input in the textarea including count in the jQuery. To set the limit character in the input textarea, we use length property. Approach: We create an input text area with a given maxlength and then use jQuery code to limit the characters. First, we set the max limit and then use keyup() method to red
1 min read
Node.js MySQL Limit Clause
LIMIT Clause is used to set the maximum size of the number of rows in the output of SQL Query. Syntax: Select only 3 rows from 1st row of users table. SELECT * FROM users LIMIT 3 Select only 3 rows from the 2nd row of the users table. SELECT * FROM users LIMIT 3 OFFSET 1 Modules: mysql: To handle MySql Connection and Queriesnpm install mysql SQL us
2 min read