Search code examples
javascriptangularjsangularjs-directiveng-messages

How to aggregate ngMessage of several field


I am using Angular JS ngMessage directive for form validation and I would like to aggregate ngMessage alert of several fields. Basically, my form contains 3 inputs (day, month, year) and I want to display alert when the date is not valid (no matter if it is the day, the month or the year that is not valid). How can I do that? I have plunkered my issue, here is how I use ngMessage directive :

<form name="messageAnimationForm">
  <label for="day">Day</label>
  <input ng-model="day" id="day" name="day" ng-minlength="1" ng-maxlength="2" required class="ngMessageSample" ng-pattern="/^\d+$/"/> <br/><br/>
  <label for="month">Month</label>
  <input ng-model="month" id="month" name="month" ng-minlength="1" ng-maxlength="2" required class="ngMessageSample" ng-pattern="/^\d+$/"/><br/><br/>
  <label for="year">Year</label>
  <input ng-model="year" id="year" name="year" ng-minlength="4" ng-maxlength="4" required class="ngMessageSample" ng-pattern="/^\d+$/"/><br/><br/>

  <div>
    <div ng-messages="messageAnimationForm.day.$error" class="ngMessagesClass" ng-messages-multiple>
      <div ng-message="pattern" class="ngMessageClass">* This field is invalid, only numbers are allowed</div>
      <div ng-message="required" class="ngMessageClass">* Day is mandatory</div>
    </div>

    <div ng-messages="messageAnimationForm.month.$error" class="ngMessagesClass" ng-messages-multiple>
      <div ng-message="pattern" class="ngMessageClass">* This field is invalid, only numbers are allowed</div>
      <div ng-message="required" class="ngMessageClass">* Month is mandatory</div>
    </div>

    <div ng-messages="messageAnimationForm.year.$error" class="ngMessagesClass" ng-messages-multiple>
      <div ng-message="pattern" class="ngMessageClass">* This field is invalid, only numbers are allowed</div>
      <div ng-message="required" class="ngMessageClass">* Year is mandatory</div>
    </div>
  </div>
</form>

Solution

  • You can check if your whole form as an error with messageAnimationForm.$error:

    <div ng-messages="messageAnimationForm.$error" class="ngMessagesClass" ng-messages-multiple>
      <div ng-message="pattern" class="ngMessageClass">* A field is invalid, only numbers are allowed</div>
      <div ng-message="minlength" class="ngMessageClass">* It's mandatory at least 1 characters</div>
      <div ng-message="maxlength" class="ngMessageClass">* It's mandatory at most 2 characters</div>
    </div>
    

    Forked your Plunker here.