Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make ngMessage for required fields only show when dirty or submitting a form?

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!

like image 387
Nicole Naumann Avatar asked Sep 03 '14 00:09

Nicole Naumann


People also ask

What is dirty in form validation?

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"

What is the difference between dirty and touched properties of a form control?

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 .


4 Answers

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>
like image 156
Eoinii Avatar answered Oct 17 '22 17:10

Eoinii


The best way to do this is with $touched:

<div class="help-block" ng-messages="userForm.name.$error" ng-show="userForm.name.$touched">
    ...
</div>
like image 41
Darren Avatar answered Oct 17 '22 17:10

Darren


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>
like image 44
John Knoop Avatar answered Oct 17 '22 17:10

John Knoop


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.

like image 11
LT86 Avatar answered Oct 17 '22 19:10

LT86