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. So the newly loaded form page is filled up with error messages. This is not what I want. How to make ngMessage for required fields only show when those fields are dirty or submitting a form?
I have read the official doc, no clue. And tried to put "ng-show = "fieldName.$dirty"" in the ng-messages div, did not work. Any help would be highly appreciated!
To prevent the validator from displaying errors before the user has a chance to edit the form, you should check for either the dirty or touched states in a control. When the user changes the value in the watched field, the control is marked as "dirty"
The difference between touched and dirty is that with touched the user doesn't need to actually change the value of the input control. touched is true of the field has been touched by the user, otherwise it's false. The opposite of touched is the property untouched .
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>
The best way to do this is with $touched:
<div class="help-block" ng-messages="userForm.name.$error" ng-show="userForm.name.$touched">
...
</div>
Only if dirty:
<div ng-messages="myForm.myField.$dirty && myForm.myField.$error">
<div ng-message='required'>Required field</div>
</div>
Only if form is submitted:
<div ng-messages="myForm.$submitted && myForm.myField.$error">
<div ng-message='required'>Required field</div>
</div>
Instead of using the ng-if suggested you could do something like...
<div ng-messages='myForm.myControl.$error' ng-if='submitted'>
<div ng-message='required'>Required field</div>
</div>
And on your submit button add:
ng-click="submitted=true"
You'd probably want to change '$scope.submitted' back to false when you type again, so you could add this to your text/email input:
ng-keyup="submitted=false"
That way only the submit button will change '$scope.submitted' to true and everything else you do will set it to false, therefore hiding your error message until you click the submit button.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With