Skip to content Skip to sidebar Skip to footer

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 prev

Solution 1:

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

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

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

Solution 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 limitif(elm[0].value.length >= scope.validLength){
              e.preventDefault();
              returnfalse;
            }
          });
        }
    }   
});

Demo in plunker

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

Solution 5:

<inputtype="text" name="usrname" maxlength="10">

use maxlength in your HTML . this is easy and effective

Post a Comment for "Angularjs Prevent Input On Textarea When Character Limit Is Reached"