user3437727
user3437727

Reputation:

AngularJS prevent input on textarea when character limit is reached

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;
        }
    });

Upvotes: 17

Views: 56856

Answers (11)

dust
dust

Reputation: 221

Just do this -

<textarea ng-model="msg" maxlength="25"></textarea>

This will definitely work!

Upvotes: 0

Thom
Thom

Reputation: 323

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

use maxlength in your HTML . this is easy and effective

Upvotes: 6

Mr. Wonderful
Mr. Wonderful

Reputation: 199

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...">

Upvotes: 2

Daniel Bonnell
Daniel Bonnell

Reputation: 4997

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.

Upvotes: 6

dbushy727
dbushy727

Reputation: 111

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>

Upvotes: 2

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>

Upvotes: 2

Mirza Kujundzic
Mirza Kujundzic

Reputation: 11

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>

Upvotes: 1

Maxim Shoustin
Maxim Shoustin

Reputation: 77904

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

Upvotes: 10

LadyQ
LadyQ

Reputation: 9

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>

Upvotes: 0

Ijon Tichy
Ijon Tichy

Reputation: 456

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>

Upvotes: 23

Rasalom
Rasalom

Reputation: 3111

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;
  }
});

Upvotes: 15

Related Questions