maxlength for AngularJS not working

2.1k Views Asked by At

I am trying to implement a maxlength functionality for a text input field.

However, whenever I go over the maxlength of 30, a message never appears saying that it's too long.

What am I doing wrong where I can implement this properly.

<div class="form-group">
                            <div class="col-sm-4">
                                <label class="control-label align-left">JV Number:</label>
                            </div>
                            <div class="col-sm-8">
                                <input type="text" ng-maxlength="30" class="form-control" placeholder="Enter JV Number" id="txtJVNumber" name="txtJVNumber" ng-model="formCtrl.AddCheckDeposit.JVNumber" />
                            </div>
                        </div> 

EDIT #1

I changed the field to the following after reading the documentation, but am still not receiving any warning.

Could you possibly let me know what the correct syntax should be?

<div class="col-sm-8">
                                <input type="text" ng-maxlength="30" class="form-control" placeholder="Enter JV Number" id="txtJVNumber" name="txtJVNumber" ng-model="formCtrl.AddCheckDeposit.JVNumber" />
                                <p class="help-block" ng-show="warrantyForm.txtJVNumber.$error.maxlength">Max characters of 30 exceeded</p>
                            </div>
1

There are 1 best solutions below

4
On

The error won't show up from itself. You have to add an html element to show the error

By using ngMessages, which is a directive that is designed to show and hide messages based on the state of a key/value object that it listens on. The directive itself complements error message reporting with the ngModel $error object (which stores a key/value state of validation errors) refer to angularJs documentation.

for example:

<div ng-messages="formName.txtJVNumber.$error" role="alert">
    <div ng-message="maxlength">Your field is too long</div>
</div>

Live demo according to your jsFiddle