5
<div class="form-group" ng-class="{'has-error': claimForm.consigneeID.$invalid && claimForm.consigneeID.$touched}">
<label class="label-bold">Consignee ID</label><br>
<input name="consigneeID" ng-model="coId" type="number" ng-maxlength="5" ng-minlength="5" class="form-control input-sm" required>
<div class="help-block" ng-messages="claimForm.consigneeID.$error" role="alert">
  <div ng-message="required">Field is required.</div>
  <div ng-message="minlength">Too few digits.</div>
  <div ng-message="maxlength">Over 5 digits.</div>         
</div>

The minlength and maxlength errors show the correct messages and correctly set the "has-error" ng-class. However, if I add "required" to my field and the corresponding message, upon reload the "Field is required" appears always (until filled in).

The red "has error" class does not appear, though, unless a different error is tripped.

What did I miss here?

Steve
  • 14,401
  • 35
  • 125
  • 230

2 Answers2

3

I am going to just summarize a couple gotcha's I ran into when using ng-messages. I believe these will answer your question and help expand the use of ng-messages.


Multiple Messages

The angular messages only allow one message by default will only display the first message that has an error. You need to tell ng-messages to allow multiple messages.

Add ng-messages-multiple to your ng-messages directive

<div class="help-block" ng-messages-multiple 
     ng-messages="claimForm.consigneeID.$error" role="alert">

Allowing Invalid Values

Something else worth adding Angular also does not always allow entry of invalid values (It will automatically clear the field on blur).

If you want to allow invalid data and display a message you may have to update your input to tell the model to allow invalid values using:

ng-model-options="{ allowInvalid: true}"

<input name="consigneeID" ng-model="coId" 
     ng-model-options="{ allowInvalid: true}"
     type="number" 
     ng-maxlength="5" ng-minlength="5" 
     class="form-control input-sm"  required>

Hide Error Messages Displaying when Form Loads

If you are looking to hide the messages when the form loads you can used the $touched attribute of the form field.

<div class="help-block" ng-messages-multiple
         ng-show="claimForm.consigneeID.$touched"
         ng-messages="claimForm.consigneeID.$error" role="alert">
Malkus
  • 3,686
  • 2
  • 24
  • 39
1

you can use ng-hide built-in directive for hiding the message and ng-show for display the message accordingly

shailendra pathak
  • 622
  • 1
  • 8
  • 25