Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS ng-messages shows error before form is even touched on Bootstrap form

<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?

like image 221
Steve Avatar asked Sep 27 '22 01:09

Steve


1 Answers

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">
like image 196
Malkus Avatar answered Oct 20 '22 17:10

Malkus