AngularJS ng-messages shows an error before the form even touches the 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> 

Errors minlength and maxlength display the correct messages and correctly set the ng class with an error. However, if I add "required" to my field and the corresponding message, when I reboot, the "Field" field always appears (before filling).

The red class "has an error", however, does not appear if another error does not work.

What am I missing here?

+5
source share
2 answers

I'm going to just sum up a couple of gotcha that I came across when using ng-messages . I believe that they will answer your question and help expand the use of ng-messages .


Multiple posts

Angular messages allow only one message by default to display only the first error message. You must 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"> 

Allow invalid values

Something else worth adding angular also does not always allow you to enter invalid values ​​(it will automatically clear the field when blurred).

If you want to resolve invalid data and display a message, you may need to update your input to inform the model of 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. Display when loading a form.

If you want to hide messages when loading a form, you can use the $touched attribute in the form field.

 <div class="help-block" ng-messages-multiple ng-show="claimForm.consigneeID.$touched" ng-messages="claimForm.consigneeID.$error" role="alert"> 
+3
source

you can use the built-in ng-hide directive to hide the message and ng-show to display the message, respectively

+1
source

Source: https://habr.com/ru/post/1237352/


All Articles