3

I am trying to make a validation with ng-messages in AngularJs 1.6.4.

But as soon as I type in in the form it shows all 3 ng-messages, and after that they won't go away until a page refresh. So even when the maxlength isn't reached it shows "your name is required".

<form name="userForm" ng-submit="signup(userForm.$valid)" novalidate>

    <!-- First name -->
    <div class="form-group" ng-class="{ 'has-error' : userForm.first_name.$touched && userForm.first_name.$invalid }">

      <label for="example-text-input" class="col-2 col-form-label">First Name</label>
      <div class="col-10">

        <input class="form-control" type="text" placeholder="Please enter your first name"
            name="first_name"
            ng-model="user.first_name"
            ng-minlength="2"
            ng-maxlength="25"
            required>

        <div class="help-block" ng-messages="userForm.first_name.$error" ng-if="userForm.first_name.$touched">
            <p ng-message="minlength">Your name is too short.</p>
            <p ng-message="maxlength">Your name is too long.</p>
            <p ng-message="required">Your name is required.</p>
        </div>

      </div>
    </div>
</form>

EDIT

Solved it by adding the ngMessages to my modules and adding the script tag in my index.html

Soundwave
  • 605
  • 2
  • 9
  • 22

2 Answers2

2

Your code work for me perfectly. check plunker link

Injecte ngmessage in your desired module.

angular.module('app', ['ngMessages'])

add angular message file in your project.

 <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular‌​-messages.js"></scri‌​pt>
Upalr
  • 2,140
  • 2
  • 23
  • 33
0
                 <input class="form-control" type="text" placeholder="Please enter your first name"
        name="first_name"
        ng-model="user.first_name"
        minlength="2"
        maxlength="25"
        ng-required="true"/>

                 <div ng-messages="userForm.first_name.$error" ng-show="userForm.first_name.$touched" >
                    <span ng-message="required"  class="error">Required</span>
                    <span ng-message="minlength">Minimum 2</span>

Maximum 25

                 </div>
twitch
  • 225
  • 1
  • 13