1

I have an input and textarea I want to limit the maximum number of characters to 20 each.How shall I do it. Assistance needed kindly.

<form novalidate name="editartistForm">
<div class="col-md-6 field_container">
    <md-input-container class="md-block log_container" flex-gt-sm>
        <label>Name</label>
            <input required type="text" name="name" ng-model="edit_artist.name">
    </md-input-container>
</div>
<div class="col-md-12 field_container">
    <md-input-container class="md-block log_container" flex-gt-sm>
        <label>Short Description</label>
             <textarea type="text" name="description" ng-model="edit_artist.description" rows="5"></textarea>
    </md-input-container>
</div>

https://jsfiddle.net/1wm5fqaa/

Musheer Aiman
  • 175
  • 1
  • 5
  • 17

1 Answers1

6

You can use maxlength html attribute to restrict the characters. You can also use ng-maxlength which will make your form invalid if it exceeds the maximum limit. But ng-maxlength will not restrict the user from inputing more characters. This is useful for form validations.

<input required type="text" name="name" ng-model="edit_artist.name" maxlength="5">
Vivz
  • 6,625
  • 2
  • 17
  • 33
  • 1
    Please don't answer obvious duplicates like these. Answering them disqualifies the (closed) duplicate from being automatically deleted. – Cerbrus Aug 31 '17 at 10:32
  • its working only for but not for – Musheer Aiman Aug 31 '17 at 10:33
  • It will work for textarea too. I suppose it t will depend on your browser. – Vivz Aug 31 '17 at 10:36
  • @Cerbrus This may contain answers from native HTML context but this question is pertaining to angularjs and I have provided answers from both perspective. – Vivz Aug 31 '17 at 10:40
  • @Vivz: Take a look at the duplicate links that are on the question, now. Those already cover everything your answer covers. – Cerbrus Aug 31 '17 at 10:41
  • @Cerbrus None of them seem to mention about angular's ng-maxlength – Vivz Aug 31 '17 at 10:42
  • Which isn't what the OP is asking about. But there's plenty of results about that as well. – Cerbrus Aug 31 '17 at 10:43
  • 1
    Op is asking from angular's perpective "How to limit the max characters in angularJS? " and I have given him suggestions about ng-maxlength and if you want to close this as a duplicate, I think you should also take this part of the duplicate answer as well and provide reference to ng-maxlength as well. – Vivz Aug 31 '17 at 10:46
  • 1
    maxlength can be edited from a browsers console and user can input more than the restricted number of characters but ng-maxlength being written in javascript will make the form invalid even if you edit from a browsers console. – Vivz Aug 31 '17 at 10:47
  • 1
    @Vivz: Look again. The answer on the _"AngularJS prevent input on textarea when character limit is reached"_ dupe ___explicitly___ states to use `ng-maxlength`. – Cerbrus Aug 31 '17 at 10:49
  • @Cerbrus My bad, You are right. :) – Vivz Aug 31 '17 at 10:57