I\'m using AngularJS 1.3.0 RC0 and angular-messages. ng-messages dutifully shows error messages for those \"required\" fields when a form is initially loaded and pristine. S
I solved this problem with a css rule
[ng-messages] { display: none; color:red; }
.ng-dirty [ng-messages] { display:block }
That's it..
Works like a charm for me.
Here is a plunker
Angular's use of classes is amazing, you can do so many things with it!
The best way to do this is with $touched:
<div class="help-block" ng-messages="userForm.name.$error" ng-show="userForm.name.$touched">
...
</div>
Do the error messages still appear after you have satisfied their conditions? In that case, have you remembered to take a dependency on ngMessages
in your angular module? E.g.:
angular.module("exampleModule", ["ngMessages"]);
<input required type="text" ng-model="model" name="field" ng-maxlength="13" ng-minlength="10">
<div ng-messages="form.field.$error" ng-if='form.$submitted'>
<p ng-message="required">Required</p>
<p ng-message="maxlength">not a valid field. Length exceeds.</p>
<p ng-message="minlength">not a valid field. Length is shorter.</p>
</div>
button type should be submit
and this will work.
Use the ng-if
attribute to check for $dirty
on the tag that has ng-messages
.
Example :
<div ng-messages='myForm.myControl.$error' ng-if='myForm.myControl.$dirty'>
<div ng-message='required'>Required field</div>
</div>
I did not want to show my message until there is any error or user tried to submit the page, and none of the above solution worked.
Finally I ended up successfully with this:
<form name='frmUser'>
..........
..........
<div ng-messages="frmUser.firstName.$error"
ng-show='frmUser.$submitted || frmUser.firstName.$dirty' role="alert">
<div ng-message="required" class="err">Required</div>
<div ng-message="maxlength" class="err">Maximum 50 characters.</div>
</div>
<input ng-model="model.first"
name="firstName"
type="text"
ng-required="true"
ng-maxlength="50"
placeholder="Enter your first name" />
</form>
If you type anything which is not valid, then show the error
If you try to submit the page and you have not provided the required field it will show error.