AngularJS prevent input on textarea when character limit is reached

All we need is an easy explanation of the problem, so here it is.

How can I stop an user from typing more characters into a textarea when a maximum amount of characters is reached?

Im using ng-keypress right now but I can’t figure out how to prevent the input when the limit is reached. The user should not be able to enter or paste more than 1000 characters in total into that textarea.

The question is about how to stop the input, not how to Count the Input lenght, this part is already working fine for me.

Plunker link.

    $scope.$watch('comment.Comment.body', function (newValue, oldValue) {
        if (newValue) {
            $scope.commentLength = 1000 - newValue.length;
        }
    });
    // Tried this, nothing stops it
    $scope.updateBody = function (event) {
        event.cancel();
        event.stop();
        return false;
    };

HTML

<textarea
    ng-model="comment.Comment.body"
    name="comment[Comment][body]"
    placeholder="Your comment..."
    ng-keypress="updateBody($event)">
</textarea>
<p>
    {{commentLength}} remaining
</p>

Solution:

My mistake was I just had a typo somewhere but the given answer is not 100% OK. Instead of using the oldValue it is required to substring() the newValue. If you don’t do that you can’t paste a text that goes over the 1000 characters into the text area. Using the newValue allows you to paste and cut the text down to the Limit.

    $scope.$watch('comment.Comment.body', function (newValue) {
        if (newValue && newValue.length > 1000) {
            $scope.comment.Comment.body = newValue.substring(0, 1000);
        }
        // Must be checked against undefined or you get problems when removing text
        if (newValue != undefined) {
            $scope.commentLength = 1000 - newValue.length;
        }
    });

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You should try using maxlength attribute. The code would be something like

<textarea
    ng-model="comment.Comment.body"
    name="comment[Comment][body]"
    placeholder="Your comment..."
    maxlength="1000">
</textarea>
<p>
    {{1000 - comment.Comment.body.length}} remaining
</p>

Method 2

You can use ‘ng-maxlength’ from angular input functionality, and watch when value is invalid.
https://docs.angularjs.org/api/ng/directive/input , but it won’t block the possibility to input.

Also you could just set a watch for value:

$scope.$watch('value', function(newVal, oldVal) {
  if(newVal.length > 10) {       
    $scope.value = oldVal;
  }
});

Method 3

Directive way:

app.directive('myBlock', function ($parse) {
    return {
        scope: {
          validLength: '='
        },
        link: function (scope, elm, attrs) {

          elm.bind('keypress', function(e){

            // stop typing if length is equal or greater then limit
            if(elm[0].value.length >= scope.validLength){
              e.preventDefault();
              return false;
            }
          });
        }
    }   
});

Demo in plunker

Method 4

All of the answers here are overly complicated and fail to leverage the power of HTML5. All you need to do is add maxlength="1000" to your input element and this will prevent the user from typing more than 1000 characters. It will also clip any pasted input to maintain the limit. See the Docs for more details.

Note that maxlength is not the same as ng-maxlength. ng-maxlength simply checks the length of the input and sets formName.$invalid if the input exceeds the limit. You can use both on the same input or textarea element.

Method 5

<input type="text" name="usrname" maxlength="10">

use maxlength in your HTML . this is easy and effective

Method 6

just adding the maxlength property to textarea solve the problem

<textarea maxlength="10"
    ng-model="comment.Comment.body"
    name="comment[Comment][body]"
    placeholder="Your comment..."
    ng-keypress="updateBody();">
</textarea>

Method 7

Although watchers do work, they are very costly due to the nature of the digest cycle, so if you need this functionality in many places you can access the change event and monitor the length.

// controller
$scope.monitorLength = function (maxLength) {
  if ($scope.value.length > maxLength) {
    $scope.value = $scope.value.substring(0, maxLength);
  }
}

// html
<textarea ng-model="value" ng-change="monitorLength(1000)"></textarea>

Method 8

Going through same problem, stumbled on this post. Below solution worked for me.

<input type="text" data-ng-model="value" class="form-control" ng-pattern="/^(\(?\+?[0-9]*\)?)?[0-9_\- \(\)]$/" ng-maxlength="15" maxlength="15" placeholder="enter your text here...">

Method 9

This works for me in template.

<textarea
    ng-model="comment.Comment.body"
    name="comment[Comment][body]"
    placeholder="Your comment..."
    maxlength="1000">
</textarea>
<p>
    {{1000 - (comment.Comment.body.length || 1000)}} remaining
</p>

Method 10

You can do this to block it

    $scope.$watch('value', function(newVal, oldVal) {
        if(newVal == undefined){
            $scope.value= oldVal;
        }
    });

    <textarea ng-maxlength="10" ng-model="value" ></textarea>

Method 11

Why angular?? when simple HTML & JavaScript can do this?

   $scope.charLimit = function($event, limitNum) {
       limitField =$event.currentTarget;
       if (limitField.value.length > limitNum) {
           limitField.value = limitField.value.substring(0, limitNum);}
   };

In HTML

 <textarea onkeyup="charLimit($event,10)" placeholder="Enter text here..."></textarea>

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply