Ad

How To Hide/show Helper Messages In Form Validation With AngularJS?

- 1 answer

I have included ngMessages into my AngularJS application to do some form validation. It's pretty useful, however I've came across something that I can't really understand.

Let's say I have this code inside my Form that is named: testForm

<input type="text" name="test1" class="form-control" ng-model="test1" required>

<span class="help-block" ng-hide="testForm.test1.$error">Please enter the a test name</span>

<div ng-messages="testForm.test1.$error" ng-if="testForm.test1.$dirty">
    <div class="text-danger" ng-message="required">This field is required</div>
</div>

I want to hide the helper message when there is an error in this textbox EXCEPT if the user hasn't started to type anything yet (on $dirty).

How is this possible? With this above code my testForm.test1.$error always gives me true value even if it's empty, therefore always hiding it.

What am I missing here?

EDIT:

I'm clarifying more what I want to achieve:

  • when typing, the helper message should be visible and the error message should be hidden
  • when there is an error, the helper message should be hidden and the error message should be visible
  • when nothing is touched yet, the helper message should be visible and the error message should be hidden
Ad

Answer

Have you tried ng-hide="testForm.test1.$error && testForm.test1.$dirty"? That way the message always displays when the input field is clean (not dirty).


Edit: As far as I see it, you want the message to be visible when input field has focus.

In your controller, initialize hasFocus to false:

$scope.hasFocus = false;

In your HTML file:

<input type="text" name="test1" class="form-control" ng-model="test1" 
  ng-focus="hasFocus=true" ng-blur="hasFocus=false" required>

<span class="help-block" ng-hide="!hasFocus && testForm.test1.$error && testForm.test1.$dirty">Please enter the a test name</span>

<div ng-messages="testForm.test1.$error" ng-if="testForm.test1.$dirty">
    <div class="text-danger" ng-message="required">This field is required</div>
</div>

You can replace ng-hide as follows if it suits you. It will hide the message when test1 is not empty and when it has error.

ng-hide="!hasFocus && testForm.test1.$error && test1"
Ad
source: stackoverflow.com
Ad